node.js 使用 fs.readFile 从外部 URL 获取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38284765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:23:36 来源:igfitidea点击:
Get File from external URL with fs.readFile
提问by Oscar A
I have links on a page that when clicked i want a external docx file to open. Unfortunately fs.readFile only reads local paths.
我在页面上有链接,单击该链接时我希望打开外部 docx 文件。不幸的是 fs.readFile 只读取本地路径。
I tried
我试过
app.get('/getfile', function (req, res) {
var externalURL = 'http://www.examplesite.com/example.docx';
// var externalURL = req.query.external;
fs.readFile(externalURL, function(err, data) {
var fileData = new Buffer(data).toString('base64');
res.send(fileData);
});
});
回答by Tiago Fabre
Try this:
尝试这个:
const http = require("http");
const file = fs.createWriteStream("file.docx");
http.get("http://www.example.com/test.docx", response => {
response.pipe(file);
});
回答by Mikey
Try node-fetch. It follows regular client syntax for the fetch command (MDN).
尝试node-fetch。它遵循 fetch 命令 ( MDN) 的常规客户端语法。

