0% found this document useful (0 votes)
2 views

4 Simple API & command line input

Uploaded by

feret82429
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

4 Simple API & command line input

Uploaded by

feret82429
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Make a simple API

 index file:-

const http = require('http');


const data = require('./data.js')

http.createServer((req, res) => {

res.writeHead(200, { 'Content-Type': 'application\JSON' });


res.write(JSON.stringify(data));
res.end();

}).listen(3000);

 data file:-

const data = [
{ name: 'Dhruvi Dhameliya', email: '[email protected]' },
{ name: 'Dhruvi Dhameliya', email: '[email protected]' },
{ name: 'Dhruvi Dhameliya', email: '[email protected]' }
];
module.exports = data;
Getting input from command line:-

 Set input from command line :-

console.log(process.argv);

 File Write :-

const fs = require('fs');

const input = process.argv;

fs.writeFileSync(input[2],input[3]);

 Add and Remove file :-

if (input[2] == 'add') {
fs.writeFileSync(input[3], input[4])
}
else if (input[2] == 'remove') {
fs.unlinkSync(input[3])
}
else {
console.log("invalid input");
}
Show file list

 Create File :-

const fs = require('fs');

fs.writeFileSync('apple.js','const demo = "file"');

 To Create File In Folder Using Loop :-

const fs = require('fs');
const path = require('path');
const dirpath = path.join(__dirname, 'files');

console.log(dirpath);
for (i = 0; i <= 5; i++) {

//fs.writeFileSync("hello"+i+".txt" , "Welcome to simba Institute.......");


fs.writeFileSync(dirpath + `/demo ${i}.js`, 'const demo = "file"');

 To Read File From Directory :-

fs.readdir(dirpath, (err, files) => {


console.log(files);
})

 Foreach Loop :-

fs.readdir(dirpath, (err, file) => {


file.forEach((item) => {
console.log("file name is ", item);
})
})

You might also like