简体   繁体   中英

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');
    });
   });
  });
 }

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 (eg 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');
    });
   });
  });
 }

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");
  });

Alternatively, you can use fs.appendFile method

let content = 'some text';
content += "\n";
fs.appendFile("helloworld.txt", content, (err) => {
    return console.log(err);
});
const { writeFileSync } = require('fs'); writeFileSync( './content/result-sync.txt', `\n Here is the result : ${first}, ${second}`, { flag: 'a' } )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM