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');
});
});
});
}
259962 次浏览

看起来你正在 Windows 上运行这个程序(给定你的 H://log.txt文件路径)。

尝试使用 \r\n而不仅仅是 \n

说实话,\n很好; 您可能在记事本中查看日志文件或其他不呈现非 Windows 换行符的内容。尝试在不同的浏览器/编辑器中打开它(例如 Wordpad)。

改为使用 os.EOL 常量。

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

使用 \r\n组合在节点 js 中添加新行

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

或者,您可以使用 附录文件方法

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

试试:

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


});

//要执行的步骤 1. 安装所有必需的模块(即这里需要 fs)。 2.Here (.common) files has json object which i was importing from another file. 3.then import the file and store in 详情 variable. 4. 在执行操作时,必须将 Json 数据转换为字符串格式(因此 JSON.stringify)。 5. WriteFileSync (它是一个同步函数) 6.once function execution is completed response is returned. 7.store response in data variable and print in console.log