Ques 16. What is the purpose of the 'fs' module in Node.js?
The 'fs' module in Node.js provides file system-related functionality. It allows reading from and writing to files, manipulating file paths, and performing other file-related operations.
Example:
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => { /* handle file content */ });
Ques 17. Explain the difference between 'exports' and 'module.exports' in Node.js.
'exports' is a shorthand reference to 'module.exports', but reassigning 'exports' directly does not work. To export an object or function, 'module.exports' should be used.
Example:
module.exports = { key: 'value' };
Ques 18. What is the purpose of the 'child_process' module in Node.js?
The 'child_process' module in Node.js is used to create child processes. It provides the 'spawn', 'exec', 'execFile', and 'fork' methods to create and interact with child processes.
Example:
const { spawn } = require('child_process');
const child = spawn('ls', ['-l']);
Ques 19. Explain the role of the 'net' module in Node.js.
The 'net' module in Node.js provides a way to create TCP servers and clients. It allows you to build networking applications, such as chat servers or custom protocols.
Example:
const net = require('net');
const server = net.createServer((socket) => { /* handle connection */ });
Ques 20. What is the purpose of the 'cluster' module in Node.js?
The 'cluster' module in Node.js allows you to create child processes that share server ports. It enables the creation of multi-core server applications, improving performance.
Example:
const cluster = require('cluster');
if (cluster.isMaster) { /* create workers */ } else { /* start server logic */ }