Javascript 如何在 Node.js 中追加到新行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10384340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append to New Line in Node.js
提问by DaBears
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?
我正在尝试使用 Node.js 将数据附加到日志文件中,这工作正常,但不会转到下一行。 \n
似乎在我下面的功能中不起作用。有什么建议?
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');
});
});
});
}
回答by Rob Hruska
It looks like you're running this on Windows (given your H://log.txt
file path).
看起来您正在 Windows 上运行它(给定您的H://log.txt
文件路径)。
Try using \r\n
instead of just \n
.
尝试使用\r\n
而不仅仅是\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).
老实说,\n
很好;您可能正在记事本或其他不呈现非 Windows 换行符的内容中查看日志文件。尝试在不同的查看器/编辑器(例如写字板)中打开它。
回答by shinzo
Use the os.EOL constant instead.
请改用 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');
});
});
});
}