Question 1: How do you print the current working directory in Node.js?
Answer: To print the current working directory in Node.js, use the following code:
console.log(__dirname);
Question 2: How do you import a module in Node.js?
Answer: To import a module in Node.js, use the following code:
const moduleName = require('module-name');
Question 3: How do you export a module in Node.js?
Answer: To export a module in Node.js, use the following code:
module.exports = {
// module code here
};
Question 4: How do you read command line arguments in Node.js?
Answer: To read command line arguments in Node.js, use the following code:
const args = process.argv.slice(2);
Question 5: How do you create a web server in Node.js?
Answer: To create a web server in Node.js, use the following code:
const http = require('http');
const server = http.createServer((req, res) => {
// server code here
});
server.listen(3000, () => {
console.log('Server started on port 3000');
});
Question 6: How do you read and parse JSON data in Node.js?
Answer: To read and parse JSON data in Node.js, use the following code:
const jsonData = require('./data.json');
Question 7: How do you write JSON data to a file in Node.js?
Answer: To write JSON data to a file in Node.js, use the following code:
const fs = require('fs');
const jsonData = {
// JSON data here
};
fs.writeFile('data.json', JSON.stringify(jsonData), err => {
if (err) throw err;
console.log('JSON data written to file');
});
Question 8: How do you read a file line by line in Node.js?
Answer: To read a file line by line in Node.js, use the following code:
const fs = require('fs');
const readline = require('readline');
const rl = readline.createInterface({
input: fs.createReadStream('file.txt'),
crlfDelay: Infinity
});
rl.on('line', line => {
console.log(`Line from file: ${line}`);
});
Question 9: How do you make an HTTP request in Node.js?
Answer: To make an HTTP request in Node.js, use the following code:
const https = require('https');
https.get('https://www.example.com', res => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
console.log(data);
});
});
Question 10: How do you use a callback function in Node.js?
Answer: To use a callback function in Node.js, use the following code:
function asyncFunction(callback) {
// asynchronous code here
callback();
}
asyncFunction(() => {
console.log('Callback function called');
});