Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js Write a line into a .txt file

Tags:

node.js

fs

I want to use Node.js to create a simple logging system which prints a line before the past line into a .txt file. However, I don't know how the file system functionality from Node.js works.

Can someone explain it?

like image 349
Meterion Avatar asked Oct 29 '15 15:10

Meterion


People also ask

CAN node js write to file?

Writing to a file is another of the basic programming tasks that one usually needs to know about - luckily, this task is very simple in Node. js. We can use the handy writeFile method inside the standard library's fs module, which can save all sorts of time and trouble.

Can JavaScript write to a text file?

There is a built-in Module or in-built library in NodeJs which handles all the writing operations called fs (File-System). It is basically a JavaScript program (fs. js) where function for writing operations is written. Import fs-module in the program and use functions to write text to files in the system.

How do I read and write node js files?

fs. writeFileSync( 'writeMe. txt' , readMe); Asynchronous method to read and write from/into a file: To read/write the file in an asynchronous mode in fs module we use readFile() and writeFile() methods.


2 Answers

Simply use fs module and something like this:

fs.appendFile('server.log', 'string to append', function (err) {    if (err) return console.log(err);    console.log('Appended!'); }); 
like image 33
michelem Avatar answered Oct 21 '22 21:10

michelem


Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback) function from fs module:

var fs = require('fs') fs.appendFile('log.txt', 'new data', function (err) {   if (err) {     // append failed   } else {     // done   } }) 

But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options]) function instead:

var fs = require('fs') var logger = fs.createWriteStream('log.txt', {   flags: 'a' // 'a' means appending (old data will be preserved) })  logger.write('some data') // append string to your file logger.write('more data') // again logger.write('and more') // again 

Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

logger.end() // close string 

Note that logger.write in the above example does not write to a new line. To write data to a new line:

var writeLine = (line) => logger.write(`\n${line}`); writeLine('Data written to a new line'); 
like image 154
Leonid Beschastny Avatar answered Oct 21 '22 20:10

Leonid Beschastny