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?
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.
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.
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.
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!'); });
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With