[英]Can I use forEach within fs.createWriteStream?
I need to create .txt file which show the content of an array line by line. 我需要创建.txt文件,以逐行显示数组的内容。 At the moment I am using the following script but file is being created but it is empty.
目前,我正在使用以下脚本,但是正在创建文件,但文件为空。
What could cause the problem? 是什么原因引起的?
var wstream = fs.createWriteStream('myOutput.txt');
[1,2,3,4].forEach(function(item){
wstream.write(item, '\n');
}.bind(this));
wstream.end();
Yes , you can use .forEach()
inside a stream write. 是的 ,您可以在流写入中使用
.forEach()
。 Your issue has nothing to do with the use of .forEach()
at all. 您的问题与
.forEach()
的使用完全无关。 Instead, you are passing the wrong arguments to .write()
. 相反,您将错误的参数传递给
.write()
。 It does not take two separate arguments that are both data for the stream like you are using it. 它不需要两个单独的参数,而这两个参数都是您正在使用的流的数据。 The function signature for
.write()
is this: .write()
的函数签名是这样的:
writable.write(chunk[, encoding][, callback])
So, when you do this: 因此,当您这样做时:
wstream.write(item, '\n');
your second argument is being interpreted as an encoding which does not work. 您的第二个参数被解释为无效的编码。 In fact, it throws an exception which you should have been able to see.
实际上,它引发了一个您应该能够看到的异常。
You can, instead, change to this: 您可以改为:
wstream.write(item + '\n');
This overall script works: 该总体脚本有效:
const fs = require('fs');
var wstream = fs.createWriteStream('myOutput.txt');
[1,2,3,4].forEach(function(item){
wstream.write(item + '\n');
});
wstream.end();
FYI, I've tried this code on my own computer with node 4.x and it works. 仅供参考,我已经在自己的节点为4.x的计算机上尝试了此代码,并且可以正常工作。
Your array is not a stream, so there's no need to use stream writing. 您的数组不是流,因此不需要使用流写入。 You can just use
fs.writeFile
and use yourArrayOfLines.join('\\n')
in as file content. 您可以只使用
fs.writeFile
并使用yourArrayOfLines.join('\\n')
作为文件内容。
var lines = [.....];
fs.writeFile('myoutput.txt', lines.join('\n'), 'utf8');
done. 完成。 Fewer lines, more obvious code behaviour (and note that the encoding is optional, it'll default to utf8 if you leave it off).
更少的行,更明显的代码行为(请注意,编码是可选的,如果不选择,则默认为utf8)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.