简体   繁体   中英

how to write array obj into file with nodejs

I'm trying with this code below, I can write file on server and the file has content but, when I download the file, it's blank.

 var file = fs.createWriteStream('./tmp/text.txt'); file.on('error', function(err) { console.log(err) }); rows.forEach(function(v) { file.write(v + "\r\n"); productExport.DeleteProduct(v.ProductId, function(err){ if(err) throw err; }); }); file.end(); var file = "./tmp/text.txt"; res.download(file); // Set disposition and send it.

How can I download the file with all the content?

The way your code is structured is incorrect for what you're trying to do. Primarily, your issue is that you're responding with res.download() before the file stream is done being written to. Additionally, you have var file being initialized twice in the same scope, this isn't correct either.

 var file = "./tmp/text.txt"; var writeStream = fs.createWriteStream(file); writeStream.on('error', err => console.log ); writeStream.on('finish', () => { return res.download(file); // Set disposition and send it. }); rows.forEach((v) => { writeStream.write(v + "\r\n"); productExport.DeleteProduct(v.ProductId, function(err){ if(err) throw err; }); }); writeStream.end();

If you're confused by this, and perhaps async processing in general, this is the defacto answer on SO for understanding async in Node.js

Writing data to a file through I/O is an asynchronous operation. You have to wait for the WriteStream to complete before you can download the file.

 var file = fs.createWriteStream('./tmp/text.txt'); file.on('error', function(err) { console.log(err) }); rows.forEach(function(v) { file.write(v + "\r\n"); productExport.DeleteProduct(v.ProductId, function(err){ if(err) throw err; }); }); file.end(); file.on('finish', function() { var file = "./tmp/text.txt"; res.download(file); // Set disposition and send it. });

Extra Information:

FileSystem#createWriteStream return WriteStream object. From the document ofWriteStream it stats there are 6 events [close, drain, error, finish, pipe, unpipe].

in the node.js world, you should always expect to use callback or seek for complete/finish event when there are I/O operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM