3.2 Using Require

Three Use Cases

FS Module & Append File

mkdir notes-node
cd notes-node/
console.log('starting app...'); // make sure it's set up
const fs = require('fs'); // fetch all contents of fs module and store them in fs constant
fs.appendFileSync('greetings.txt', 'Hello World!');
node app.js
starting app...

Alt text

node app.js
starting app...
node app.js
starting app...

In the created file, we will see the string twice!

Alt text

OS Module & UserInfo

console.log('starting app...');
const fs = require('fs');
const os = require('os');
var user = os.userInfo();
console.log(user);
starting app...
{ uid: 501,
gid: 20,
username: 'xingao',
homedir: '/Users/xingao',
shell: '/bin/bash' }
console.log('starting app...');
const fs = require('fs');
const os = require('os');
var user = os.userInfo();
fs.appendFileSync('greetings.txt', 'Hello' + user.username + '!');

Alt text

fs.appendFileSync('greetings.txt', `Hello ${user.username}!`);