Node JS basics

Reading file

fs.readFile('notes.log', function(err, data) {
    if(err) throw err;
    console.log(data.toString());
});

Get file lines

fs.readFile('customlog.log', function(err, data) {
    if(err) throw err;
    var fileLines = data.toString().split("\n");
    console.log(fileLines);
});

Write file

arr = fs.writeFile("./note.txt", "hello", function(err) {
    if( err ) throw err;
    console.log("hello > 2.js");
})

Create directory

fs.mkdir('folder1', function(e) {
    if(e && e.code === 'EEXIST') {
        console.log(e);
    } else {
        console.log('folder create');
    }
});

Custom log + passing arguments

var myArgs = process.argv.slice(2);
const format = require("node.date-time");
function logTime() { return new Date().format("Y-M-d H:M:S"); }
fs.appendFile('customlog.log', logTime() + " " + myArgs + " " + "\n", function(err) {
    if(err) throw err;
    console.log('saved');
});

Useful

– PM2 is a process manager for the JavaScript runtime Node.js.

NodeJS docs

Examples link

 

Libraries:

For creating logs: node.date-time

Was this article helpful?

Related Articles

Leave A Comment?