Or Smith
Or Smith

Reputation: 3596

node.js / Writing files from response

I send the next POST request:

var post_data = JSON.stringify({
    'uuid': '00d25',
    'file': 'ORIGINAL',
    'store' : 'someStore'
});
console.log("B");
// An object of options to indicate where to post to
var post_options = {
    'host': 'localhost',
    'port': '5000',
    'path': '/getDocu',
    'method': 'POST',
    'headers': {
        'Content-Type': 'application/json'
    }
};

// Set up the request
var post_req = http.request(post_options, function(res) {
       // Here I need to get the data response
}

I want to create a file, and put all the data I get from the response. So I try this:

 res.setEncoding('utf8');
        var writeStream = fs.createWriteStream("C://Client//something4.txt");

        res.on('data', function (chunk) {
            writeStream.write(chunk);
        });
        res.on('end', function () {
            writeStream.close();
        })

But I see that I get only some part of this file (65KB/258KB), and not the whole file.

What I do wrong?

Upvotes: 0

Views: 48

Answers (1)

Jerome WAGNER
Jerome WAGNER

Reputation: 22412

You are probably closing the file handle before you got a chance to write everything to disk.

Since res is a Stream, you should try the following:

res.setEncoding('utf8');
var writeStream = fs.createWriteStream("C://Client//something4.txt");
res.pipe(writeStream);

Upvotes: 1

Related Questions