Reputation: 2495
I have a function fetching json data from postgres on click of a button. What I want is to save that data in a zipped file. I'm new to nodeJS, so I'm not entirely sure how writestreams and pipes work. This is what I have:
module.exports.fileDownload = function(req, res){
var id = req.query.id;
postgresService.getJsonData(id)
.then(response => {
const writer = fs.createWriteStream('my_file.json');
// logger.info(response);
// logger.info(writer);
writer.write(response)
res.pipe(writer);
})
.catch(err => {
logger.info('Something went wrong');
logger.info(err);
})
}
I thought I'd figure out a way to use zlib once I at least get the file, but even at this stage, though my logger shows the response and the writer correctly, it ends up in the catch block. The error I keep seeing is:
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer
I should mention that the response is a fairly big json object.
I've played around with the code but can't get it to work. Some sources mention that you need to create a readstream to pipe to a writestream, but I'm not sure where in my code to do that.
Can anyone help?
Upvotes: 0
Views: 567
Reputation: 7770
try this
module.exports.fileDownload = function(req, res){
var id = req.query.id;
postgresService.getJsonData(id)
.then(response => {
const writer = fs.createWriteStream('my_file.json');
// logger.info(response);
// logger.info(writer);
writer.write(JSON.stringify(response));
res.pipe(writer);
})
.catch(err => {
logger.info('Something went wrong');
logger.info(err);
})
}
Basically you need to convert it to string so some other type as you wouldn't be able to write an object to write stream.
Upvotes: 1