beginerdeveloper beginerdeveloper - 9 days ago 5
Node.js Question

how to write array obj into file with nodejs

i am trying with this code below, i can write file on server and the file have the content but when i download the file, the file is 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.


pls help me fix this code how can i download the file with all the content

Answer

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 of WriteStream 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.

Comments