Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append to New Line in Node.js

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');     });    });   });  } 
like image 929
DaBears Avatar asked Apr 30 '12 13:04

DaBears


People also ask

How do I append in node JS?

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.

How do you break in node JS?

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.

How do I go to console in New Line?

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.

How do you start a new line in a for loop?

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.


2 Answers

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).

like image 62
Rob Hruska Avatar answered Sep 19 '22 10:09

Rob Hruska


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');     });    });   });  } 
like image 21
shinzo Avatar answered Sep 23 '22 10:09

shinzo