130

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');
    });
   });
  });
 }
buydadip
  • 8,890
  • 22
  • 79
  • 154
DaBears
  • 1,693
  • 3
  • 14
  • 17
  • 4
    Are you on Windows/using a Windows-based text editor to view your file, and thus need a CRLF pair, `\r\n`? – Phrogz Apr 30 '12 at 13:17

5 Answers5

203

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

Rob Hruska
  • 118,520
  • 32
  • 167
  • 192
129

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');
    });
   });
  });
 }
shinzo
  • 1,299
  • 1
  • 8
  • 2
  • 23
    (1/2) Please note that since node.js can run on many different environments, it may be possible to move your application from lets say a windows environment to a linux one. that means if your application is appending logs using `os.EOL` you will have some lines ending with `/r/n` (from the time app was running on windows) and then you will have rows ending just with `/n` (when app runs on linux). This has the potential to give some trouble especially if any automatic parsing of log files is in place. I decided to just use `/n`. – Sharky May 24 '16 at 08:58
  • 4
    (2/2) Nevertheless i upvoted your answer as it would be the correct one, if we lived in a perfect-regulated world. – Sharky May 24 '16 at 09:01
  • 1
    I use linux but liked this approach as I might want portability in future use. –  Aug 01 '16 at 03:40
  • 1
    This is the best answer because it works crossplatform. – Mike Chelen Sep 07 '18 at 19:29
  • Well, I had to package an application that used `fs.write` with `os.EOL` into a binary. I used `pkg` to generate a binary for Windows. When executed, the last written record has a new line appended to it (as expected); but, seems like other Windows applications treat it is a new record. I am hunting for a work-around. – cogitoergosum Oct 23 '18 at 05:36
  • Maybe, add that splitting file data into lines could be done with a regular expression (e.g.: /(\r\n|\n\r|\r|\n)/) to properly read files from all various systems. – Alex_M Sep 05 '20 at 11:01
  • Here's how java.util.Scanner does it - http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Scanner.java#l455 – Alex_M Sep 05 '20 at 11:22
11

use \r\n combination to append a new line in node js

  var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });
Codemaker2015
  • 12,190
  • 6
  • 97
  • 81
6

Alternatively, you can use fs.appendFile method

let content = 'some text';
content += "\n";
fs.appendFile("helloworld.txt", content, (err) => {
    return console.log(err);
});
hamon
  • 103
  • 3
  • 9
-3

Try:

var fs =require('fs');

const details=require('./common');
var info=JSON.stringify(details);

const data=fs.writeFileSync('./tmp/hello/f1.txt',`\n${info}`,{'flag':'a'},function(err,data){
    
if(err) return console.error("error",error);
    console.log(data);

});

//steps to exceute 1.Install all the required modules(ie fs is required here). 2.Here (.common) files has json object which i was importing from another file. 3.then import the file and store in details variable. 4.While performing operations json data has to be converted into string format (so JSON.stringify). 5.WriteFileSync (its an synchronous function) 6.once function execution is completed response is returned. 7.store response in data variable and print in console.log