Sometimes, we want to append to new line in Node.js.
In this article, we’ll look at how to append to new line in Node.js.
How to append to new line in Node.js?
To append to new line in Node.js, we can use the write
method with the os.EOL
constant.
For instance, we write
const os = require("os");
const fs = require("fs");
fs.open('./log.txt', 'a', 666, (e, id) => {
fs.write(id, text + os.EOL, null, 'utf8', () => {
fs.close(id, () => {
console.log('file is updated');
});
});
});
to call fs.open
to open the ./log.txt
file with 666 file permission and 'a'
for append.
Then we call fs.write
with the text
appended with the os.EOL
character, which is the new line character for the platform the app is running on.
Then we call fs.close
to close the file handle given by id
.