如何执行多个.write()命令?

时间:2017-03-06 02:59:53

标签: node.js

我在节点JS中有我的代码,如何执行多个.write()命令?这段代码的输出将创建一个test.xls文件,当我打开该文件时,它只显示第一个writeStream.write,它是标题(" Sl No" +" \ t" +"年龄" +" \ t" +"名称" +" \ n")我想要所有这些(标题,第1行, row2)一起执行并在test.xls文件上显示所有这些



exports.post = function(req, res){

var writeStream = fs.createWriteStream("test.xls");
var header="Sl No"+"\t"+" Age"+"\t"+"Name"+"\n";
var row1 = "0"+"\t"+" 21"+"\t"+"Rob"+"\n";
var row2 = "1"+"\t"+" 22"+"\t"+"bob"+"\n";

writeStream.write(header);
writeStream.write(row1);
writeStream.write(row2);
writeStream.close();
	 
};




1 个答案:

答案 0 :(得分:1)

尝试一次性写入它们是一个快速修复:

writeStream.write(header + '\n' + row1 + '\n' + row2);
writeStream.close();

使用.end vs .close因为节点是异步的。根据我的理解end等待所有可写的块完成,close终止流。

writeStream.write(header);
writeStream.write(row1);
writeStream.write(row2);
writeStream.end();
close and error events are emitted when a stream ends due to failure (e.g. stream.destroy())
end is emitted when a readable stream has no more data

source