I'm trying to Append data to a Log file using Node.js and that is working fine but it is not going to the next line. \n
doesn't seem to be working in my function below. Any suggestions?
function processInput ( text ) { fs.open('H://log.txt', 'a', 666, function( e, id ) { fs.write( id, text + "\n", null, 'utf8', function(){ fs.close(id, function(){ console.log('file is updated'); }); }); }); }
To append data to file in Node. js, use Node FS appendFile() function for asynchronous file operation or Node FS appendFileSync() function for synchronous file operation.
For html you have to replace your \n with a break (<br>), specify in the css that the browser should respect your linebreaks or wrap it in a <pre> or alike statement.
To create a multi line strings when printing to the JavaScript console, you need to add the new line character represented by the \n symbol. Alternatively, you can also add a new line break using Enter when you use the template literals syntax.
Add "\n". That'll precede the whole value with a newline. You'd be better putting it after ;) That's true - it would add an unnecessary line before everything else.
It looks like you're running this on Windows (given your H://log.txt
file path).
Try using \r\n
instead of just \n
.
Honestly, \n
is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).
Use the os.EOL constant instead.
var os = require("os"); function processInput ( text ) { fs.open('H://log.txt', 'a', 666, function( e, id ) { fs.write( id, text + os.EOL, null, 'utf8', function(){ fs.close(id, function(){ console.log('file is updated'); }); }); }); }
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