0

I'm trying to download a json file from an external url using nodejs. The problem is that this file (dumpFile.json) is created empty.

var file = fs.createWriteStream("download/dumpFile.json");
let URL = 'http://user:pass@domain.com/file.json');
var request = http.get(URL, function (resp) {
     resp.on("finish", function () {
       logger.error(fs.readFileSync("file", { encoding: "utf8" }))
 }).pipe(file);
});
}).catch(error => {
  logger.error(error)  
})

I tried a lot of things, but I can't figured it out what is happening.

mr.abdo
  • 445
  • 1
  • 5
  • 15

2 Answers2

0
const fs = require('fs')
const http = require('http')

const url = 'http://user:pass@domain.com/file.json'
const fileName = 'download/dumpFile.json'

http.get(url, function (res) {
  res.pipe(fs.createWriteStream(fileName))
})
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
  • it work's on localhost but doesnt works on production and there's no proxy or something like that. – mr.abdo Aug 14 '19 at 14:15
  • Make sure your handling errors properly - the above example is missing that. You can do a `try/catch` and/or `.catch` at the end of the `http.get()` call, like in this example - https://stackoverflow.com/a/8541020/5862900 – goto Aug 15 '19 at 14:56
0

I think you are calling to a https url using http try this working code.

var http = require('https');
var fs = require("fs");
var file = fs.createWriteStream("dumpFile.json");
let URL = 'https://raw.githubusercontent.com/ljharb/json-file-plus/master/package.json';
try {
    var request = http.get(URL, function (resp) {
        resp.on("finish", function () {
            logger.error(fs.readFileSync("file", {
                encoding: "utf8"
            }))
        }).pipe(file);
    });
} catch (e) {
    console.log('error ', e);
}

sorry your code seems to be incomplete, I was updated it to check working.

PRAJIN PRAKASH
  • 1,366
  • 1
  • 15
  • 31
  • it work's on localhost but doesnt works on production and there's no proxy or something like that. – mr.abdo Aug 14 '19 at 14:15