javascript - วิธีการเพิ่มบรรทัดใหม่ใน Node.js
ฉันกำลังพยายามเพิ่มข้อมูลลงในไฟล์ Log โดยใช้ 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');
});
});
});
}
คำตอบ #1
ดูเหมือนว่าคุณกำลังใช้งานนี้บน Windows (ตามเส้นทางไฟล์ H://log.txt ของคุณ)
ลองใช้ \r\n แทนที่จะใช้แค่ \n
พูดตามตรง, \n ใช้ได้ดี; คุณอาจจะกำลังเปิดไฟล์ล็อกในโน้ตแพดหรือโปรแกรมอื่นที่ไม่รองรับการขึ้นบรรทัดแบบนอกวินโดวส์ ลองเปิดในโปรแกรมดู/แก้ไขอื่น (เช่น Wordpad)
คำตอบ #2
ใช้ค่าคงที่ 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');
});
});
});
}
คำตอบ #3
ใช้ \r\n เพื่อเพิ่มบรรทัดใหม่ใน Node.js
var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
stream.once('open', function(fd) {
stream.write(msg+"\r\n");
});
