Welcome to the NodeCodes for learning!!
This repo is intended to provide beginner to intermediate level Node.js developers with a set of questions and answers that can help them improve their skills and knowledge of this JavaScript runtime environment. These are coding question generated by ChatGPT and I have written codes to these question as per my knowledge gained from reading docs on Node.js and the libraries and node packages.
- Write a function in Node.js that reads a file named "data.txt" and logs its contents to the console
- Write a function in Node.js that creates a new directory named "logs" and logs a message to a file named "info.log" inside the directory
- Write a function in Node.js that fetches data from an API endpoint using the Axios library and returns the response
- Write a function in Node.js that uses the native "http" module to create a simple HTTP server that listens on port 3000 and returns a "Hello, world!" message to any incoming request
- Write a function in Node.js that accepts a command-line argument and logs it to the console
- Write a function in Node.js that reads a CSV file named "data.csv" and converts its contents to JSON format
- Write a function in Node.js that uses the "fs" module to recursively list all files and directories in a given directory
- Write a function in Node.js that accepts a POST request containing JSON data and saves it to a file named "data.json"
- Write a function in Node.js that uses the "crypto" module to generate a random 32-byte hexadecimal string
- Write a function in Node.js that uses the "cluster" module to create a simple cluster of worker processes that each log a message to the console
- Write a function that returns a Promise which resolves with a random number after a delay of 1 second
- Write a function that returns a Promise which rejects with an error message after a delay of 500ms
- Write a function that takes an array of numbers as input and returns a Promise which resolves with the sum of all the numbers in the array
- Write a function that takes an array of Promises as input and returns a Promise which resolves with an array of resolved values from the input Promises
- Write a function that fetches data from an API endpoint using the Axios library and returns a Promise which resolves with the response data. The function should reject the Promise if the API request fails
1. Write a function in Node.js that reads a file named "data.txt" and logs its contents to the console
const fs = require('fs')
function logFileContent(){
fs.readFile('./data.txt', 'utf-8' ,(err,data)=>{
if(err) throw err;
console.log(data);
})
}
logFileContent();
2. Write a function in Node.js that creates a new directory named "logs" and logs a message to a file named "info.log" inside the directory
const fs = require('fs');
function logToFile(){
let myData = 'Logging to file info.log'
fs.mkdir('./logs', { recursive: true }, (err) => {
if(err)
throw err
else {
fs.writeFile('./logs/info.log', myData ,(err) => {
if(err) throw err;
});
}
});
}
logToFile();
3. Write a function in Node.js that fetches data from an API endpoint using the Axios library and returns the response
const axios = require('axios');
async function fetchData(){
try {
const data = await axios.get('https://random-data-api.com/api/v2/users');
return data;
} catch (error) {
throw error;
}
}
fetchData()
.then(data => console.log(data.data))
.catch(error => console.log(error));
4. Write a function in Node.js that uses the native "http" module to create a simple HTTP server that listens on port 3000 and returns a "Hello, world!" message to any incoming request.
const http = require('http');
http.createServer((req,res)=>{
res.end('Hello World!!')
}).listen(3000);
function getArgs(){
let args = process.argv.slice(2);
console.log(args)
}
getArgs();
6. Write a function in Node.js that reads a CSV file named "data.csv" and converts its contents to JSON format
const fs = require('fs').promises;
async function csvToJSON(){
let data = await fs.readFile('./data.csv','utf8');
let arr = data.split('\n');
let json = [];
let keys = arr[0].split(',');
for(let i=1;i<arr.length;i++){
let obj = {};
let values = arr[i].split(',');
for(let j=0;j<keys.length;j++){
obj[keys[j]] = values[j];
}
json[i-1] = obj;
}
return JSON.stringify(json);
}
csvToJSON().then(data => console.log(data));
7. Write a function in Node.js that uses the "fs" module to recursively list all files and directories in a given directory
const fs = require('fs');
const path = require('path');
function listFiles(){
let directoryPath = '../'
fs.readdir(directoryPath,(err,directories)=>{
if(err) throw err;
directories.forEach((directory)=>{
fs.readdir(path.join(__dirname,'/..',directory),(err,files)=>{
console.log('Directory: ', directory,'files: ',files);
})
})
})
}
listFiles()
8. Write a function in Node.js that accepts a POST request containing JSON data and saves it to a file named "data.json"
const http = require('http');
const fs = require('fs');
http.createServer((req,res)=>{
if(req.method === 'POST' && req.url === '/'){
req.on('data',(chunk)=>{
fs.writeFile('./data.json',chunk,(err)=>{
if(err) throw err;
})
});
res.end();
}
}).listen(3000);
9. Write a function in Node.js that uses the "crypto" module to generate a random 32-byte hexadecimal string
const crypto = require('crypto');
function getRandomHex(){
let bytes = crypto.randomBytes(32).toString('hex');
console.log(bytes);
}
getRandomHex();
10. Write a function in Node.js that uses the "cluster" module to create a simple cluster of worker processes that each log a message to the console
const cluster = require('cluster');
const { availableParallelism } = require('os');
const numCPUs = availableParallelism();
function generateClusters(){
if(cluster.isPrimary){
console.log("Primary Cluster: ", process.pid);
for(let i=0;i<numCPUs;i++){
let worker = cluster.fork();
worker.on('online',()=>{
console.log('Worker online: ', worker.process.pid);
})
}
}
}
generateClusters();
11. Write a function that returns a Promise which resolves with a random number after a delay of 1 second
function randomPromise(){
let p = new Promise((resolve,reject)=>{
setTimeout(() => {
resolve(Math.floor(Math.random() * 100));
}, 1000);
})
return p;
}
randomPromise().then(data=>console.log(data));
12. Write a function that returns a Promise which rejects with an error message after a delay of 500ms
function rejectPromise(){
let p = new Promise((resolve,reject)=>{
setTimeout(() => {
reject(new Error('Error Message'));
}, 500);
});
return p;
}
rejectPromise().catch(err=>console.log(err));
13. Write a function that takes an array of numbers as input and returns a Promise which resolves with the sum of all the numbers in the array
function sumArray(arr){
let p = new Promise((resolve,reject)=>{
let sum = arr.reduce((acc,current)=> acc+=current);
resolve(sum);
});
return p;
}
sumArray([1,2,3,4]).then(data=>console.log(data));
14. Write a function that takes an array of Promises as input and returns a Promise which resolves with an array of resolved values from the input Promises
function resolvePromise(p){
return Promise.all(p)
}
let p1 = Promise.resolve(1);
let p2 = Promise.resolve(2);
let p3 = Promise.resolve(3);
resolvePromise([p1,p2,p3]).then(data=>console.log(data)).catch(err=>console.log(err));
15. Write a function that fetches data from an API endpoint using the Axios library and returns a Promise which resolves with the response data. The function should reject the Promise if the API request fails
const axios = require('axios')
function fetchData(){
return axios.get('https://random-data-api.com/api/v2/users')
.then((data)=>data.data)
.catch((error)=>error);
}
fetchData().then(data=>console.log(data)).catch(err=>console.log(err));