1. Create Custom / Local Modules and Export Them Using Various Module Patterns
a. CommonJS Pattern (module.exports)
mathUtils.js:
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
module.exports = { add, subtract };
app.js:
const math = require('./mathUtils');
console.log(math.add(5, 3)); // 8
console.log(math.subtract(9, 4)); // 5
b. Exports Shortcut Pattern
greet.js:
exports.sayHello = (name) => `Hello, ${name}!`;
exports.sayBye = (name) => `Bye, ${name}!`;
app.js:
const greet = require('./greet');
console.log(greet.sayHello('Sam')); // Hello, Sam!
c. Immediately Invoked Function Expression (IIFE)
counter.js:
module.exports = (function () {
let count = 0;
return {
increment: () => ++count,
decrement: () => --count,
};
})();
app.js:
const counter = require('./counter');
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
2. Explore the Functionality of os, path, util, and events Modules
os Module:
const os = require('os');
console.log(os.platform());
console.log(os.cpus());
console.log(os.freemem());
path Module:
const path = require('path');
console.log(path.basename(__filename));
console.log(path.join(__dirname, 'files', 'test.txt'));
util Module :
const util = require('util');
const wait = util.promisify(setTimeout);
wait(1000).then(() => console.log('1 second passed'));
events Module :
const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('greet', (name) => {
console.log(`Hello, ${name}`);
});
emitter.emit('greet', 'Alice');
3. Use the fs Module for Creating Directories and Files of Different Formats
const fs = require('fs');
const path = require('path');
// Create directory
fs.mkdirSync(path.join(__dirname, 'output'), { recursive: true });
// Create text file
fs.writeFileSync(path.join(__dirname, 'output', 'note.txt'), 'This is a text file.');
// Create JSON file
const data = { name: 'Node', type: 'runtime' };
fs.writeFileSync(path.join(__dirname, 'output', 'data.json'), JSON.stringify(data, null, 2));
4. Read and Write Streaming Data Using Readable and Writable Streams
const fs = require('fs');
const path = require('path');
// Create read and write streams
const readStream = fs.createReadStream(path.join(__dirname, 'input.txt'), 'utf-8');
const writeStream = fs.createWriteStream(path.join(__dirname, 'output', 'output.txt'));
// Pipe data from input.txt to output.txt
readStream.pipe(writeStream);
Make sure to create an input.txt file before running this.
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter