Node.js 将一行写入 .txt 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33418777/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:26:49  来源:igfitidea点击:

Node.js Write a line into a .txt file

node.jsfs

提问by Meterion

I want to create a simple Log System, which prints a line before the past line into a txt file by using Node.js, but i dont know how the File System from Node.js works. Can someone explain it ?

我想创建一个简单的日志系统,它使用 Node.js 将过去行之前的一行打印到 txt 文件中,但我不知道 Node.js 的文件系统是如何工作的。有人可以解释一下吗?

回答by Leonid Beschastny

Inserting data into the middle of a text file is not a simple task. If possible, you should append it to the end of your file.

将数据插入文本文件的中间并不是一项简单的任务。如果可能,您应该将其附加到文件的末尾。

The easiest way to append data some text file is to use build-in fs.appendFile(filename, data[, options], callback)functionfrom fsmodule:

追加数据的一些文本文件,最简单的方法是使用内置的fs.appendFile(filename, data[, options], callback)功能fs模块

var fs = require('fs')
fs.appendFile('log.txt', 'new data', function (err) {
  if (err) {
    // append failed
  } else {
    // done
  }
})

But if you want to write data to log file several times, then it'll be best to use fs.createWriteStream(path[, options])functioninstead:

但是如果你想多次将数据写入日志文件,那么最好使用fs.createWriteStream(path[, options])函数

var fs = require('fs')
var logger = fs.createWriteStream('log.txt', {
  flags: 'a' // 'a' means appending (old data will be preserved)
})

logger.write('some data') // append string to your file
logger.write('more data') // again
logger.write('and more') // again

Node will keep appending new data to your file every time you'll call .write, until your application will be closed, or until you'll manually close the stream calling .end:

每次您调用 时.write,Node 都会将新数据附加到您的文件中,直到您的应用程序关闭,或者直到您手动关闭流调用.end

logger.end() // close string

回答by michelem

Simply use fsmodule and something like this:

只需使用fs模块和类似的东西:

fs.appendFile('server.log', 'string to append', function (err) {
   if (err) return console.log(err);
   console.log('Appended!');
});

回答by Yene Mulatu

Step 1

第1步

If you have a small file Read all the file data in to memory

如果你有一个小文件 将所有文件数据读入内存

Step 2

第2步

Convert file data string into Array

将文件数据字符串转换为数组

Step 3

第 3 步

Search the array to find a location where you want to insert the text

搜索数组以找到要插入文本的位置

Step 4

第四步

Once you have the location insert your text

一旦你有位置插入你的文字

yourArray.splice(index,0,"new added test");

Step 5

第 5 步

convert your array to string

将您的数组转换为字符串

yourArray.join("");

Step 6

第 6 步

write your file like so

像这样写你的文件

fs.createWriteStream(yourArray);

This is not advised if your file is too big

如果您的文件太大,则不建议这样做

回答by ISURU THIWANKA

I did a log file which prints data into text file using "Winston" log. The source code is here below,

我做了一个日志文件,它使用“Winston”日志将数据打印到文本文件中。源代码在下面,

const { createLogger, format, transports } = require('winston');
var fs = require('fs')
var logger = fs.createWriteStream('Data Log.txt', {`
flags: 'a' 
})
const os = require('os');
var sleep = require('system-sleep');
var endOfLine = require('os').EOL;
var t = '             ';var s = '         ';var q = '               ';
var array1=[];
var array2=[];
var array3=[];
var array4=[];

array1[0]  =  78;`
array1[1]  =  56;
array1[2]  =  24;
array1[3]  =  34;

for (var n=0;n<4;n++)
{
array2[n]=array1[n].toString();
}

for (var k=0;k<4;k++)
{
array3[k]=Buffer.from('                    ');
}

for (var a=0;a<4;a++)  
{
array4[a]=Buffer.from(array2[a]);
}

for (m=0;m<4;m++)
{
array4[m].copy(array3[m],0);
}

logger.write('Date'+q);
logger.write('Time'+(q+'  '))
logger.write('Data 01'+t);
logger.write('Data 02'+t); 
logger.write('Data 03'+t);
logger.write('Data 04'+t)

logger.write(endOfLine);
logger.write(endOfLine);
enter code here`enter code here`
}

function mydata()      //user defined function
{
logger.write(datechar+s);
logger.write(timechar+s);
for ( n = 0; n < 4; n++) 
{
logger.write(array3[n]);
}
logger.write(endOfLine); 
}

for (;;)
}
var now = new Date();
var dateFormat = require('dateformat');
var date = dateFormat(now,"isoDate");
var time = dateFormat(now, "h:MM:ss TT ");
var datechar = date.toString();
var timechar = time.toString();
mydata();
sleep(5*1000);
}