简体   繁体   English

如何从外部URL下载json文件

[英]How to download json file from external URL

I'm trying to download a json file from an external url using nodejs. 我正在尝试使用nodejs从外部URL下载json文件。 The problem is that this file ( dumpFile.json ) is created empty. 问题在于此文件( dumpFile.json )创建为空。

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. 我尝试了很多事情,但是我无法弄清楚发生了什么。

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))
})

I think you are calling to a https url using http try this working code. 我认为您正在使用http调用https网址,请尝试此工作代码。

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. 抱歉,您的代码似乎不完整,我对其进行了更新以检查其工作情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM