0

I've searched everywhere for a solution to this problem, but it is nowhere to be found. Here is the function I am using:

var file = fs.createWriteStream(dest);
http.request(url, function(res) {
   res.pipe(file);
});

It's supposed to write the contents of the file specified within the url to a new file on my computer using fs.createWriteStream(). It creates the file on my computer, but the problem is is that the file is empty. It doesn't actually "write" the contents of the file specified with the url to the new file.

Any help with this issue would be greatly appreciated! I've been trying to fix this for hours.

m-byte
  • 115
  • 1
  • 1
  • 6
  • What "file specified within url" here means? download URL for that file? if so, you can download and save to a location. – Sridhar Jul 19 '17 at 03:47
  • It basically means copying the contents of the file (http://example.com/file.txt) to a new file on my PC, so the new file that was just created would have the same contents as the one on the site. But downloading it and saving it to a location would work just as well – m-byte Jul 19 '17 at 04:45
  • Your syntax looks correct. Are you sure that the request is successful? I would suggest putting some error handling in ```const req = http.request(...``` Catch any error on the request:```req.on('error', (e) => { console.error(`problem`)})``` Catch error on the writestream:```writeStream.on('error', function (err) { console.log(err);});``` – Peter Grainger Jul 19 '17 at 05:13
  • I tried that, no error, no logs, nothing. Just an empty file :/ – m-byte Jul 19 '17 at 19:36
  • Holdon, I left the console running for about 10 minutes and it finally threw an error! (Never thought I'd be so happy to get an error, haha) I tried your second method of catching errors on both the request and writestream, the only one that threw an error was on the request. Here's what I got: https://imgur.com/a/OfOef Any idea on how I can avoid this? Thanks :) – m-byte Jul 19 '17 at 20:19
  • Is this a duplicate of https://stackoverflow.com/q/12906694/841830 ? I.e. when using pipe() you need to wait for the open event. – Darren Cook Oct 24 '17 at 16:11

0 Answers0