Ques 21. Explain the purpose of the 'crypto' module in Node.js.
The 'crypto' module provides cryptographic functionality in Node.js. It allows for the generation of hashes, HMAC (Hash-based Message Authentication Code), and various encryption/decryption algorithms.
Example:
const crypto = require('crypto');
const hash = crypto.createHash('sha256').update('Hello').digest('hex');
Ques 22. What is the purpose of the 'url' module in Node.js?
The 'url' module provides utilities for URL resolution and parsing. It allows working with URLs, including parsing query parameters and formatting URL components.
Example:
const url = require('url');
const parsedUrl = url.parse('https://example.com/path?query=value', true);
Ques 23. Explain the concept of 'npm scripts' in package.json.
npm scripts are user-defined scripts that can be run using the 'npm run' command. They are defined in the 'scripts' section of the 'package.json' file and can be used for various tasks such as testing, building, or starting the application.
Example:
"scripts": { "start": "node index.js", "test": "mocha test/*.js" }
Ques 24. How can you handle errors in Node.js applications?
Errors in Node.js can be handled using try-catch blocks, using the 'error' event in asynchronous operations, or by using middleware functions in frameworks like Express.js to catch errors globally.
Example:
try { /* code that may throw an error */ } catch (error) { /* handle error */ }
Ques 25. What is the purpose of the 'event emitters' in Node.js?
Event emitters in Node.js allow objects to emit named events that cause functions (listeners) to be called. They are at the core of Node.js's event-driven architecture and are used throughout the standard library.
Example:
const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => console.log('Event emitted'));