如何在不使用第三方库的情况下使用Node.js下载文件?
我不需要什么特别的东西。我只想从给定的URL下载文件,然后将其保存到给定的目录。
如何在不使用第三方库的情况下使用Node.js下载文件?
我不需要什么特别的东西。我只想从给定的URL下载文件,然后将其保存到给定的目录。
当前回答
没有库,它可能是错误的,只是指出。以下是一些例子:
不能处理http重定向,比如这个url https://calibre-ebook.com/dist/portable,它是二进制的。 http模块不能https url,你将得到协议“https:”不支持。
以下是我的建议:
调用系统工具,如wget或curl 使用一些类似node-wget-promise的工具,使用起来也非常简单。 Var wget = require('node-wget-promise'); wget(“http://nodejs.org/images/logo.svg”);
其他回答
没有库,它可能是错误的,只是指出。以下是一些例子:
不能处理http重定向,比如这个url https://calibre-ebook.com/dist/portable,它是二进制的。 http模块不能https url,你将得到协议“https:”不支持。
以下是我的建议:
调用系统工具,如wget或curl 使用一些类似node-wget-promise的工具,使用起来也非常简单。 Var wget = require('node-wget-promise'); wget(“http://nodejs.org/images/logo.svg”);
您可以创建一个HTTP GET请求,并将其响应管道到可写文件流:
const http = require('http'); // or 'https' for https:// URLs
const fs = require('fs');
const file = fs.createWriteStream("file.jpg");
const request = http.get("http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg", function(response) {
response.pipe(file);
// after download completed close filestream
file.on("finish", () => {
file.close();
console.log("Download Completed");
});
});
如果您希望支持在命令行上收集信息(比如指定目标文件或目录或URL),可以使用类似Commander的工具。
更详细的解释在https://sebhastian.com/nodejs-download-file/
也许node.js已经改变了,但似乎其他解决方案(使用node v8.1.2)有一些问题:
You don't need to call file.close() in the finish event. Per default the fs.createWriteStream is set to autoClose: https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options file.close() should be called on error. Maybe this is not needed when the file is deleted (unlink()), but normally it is: https://nodejs.org/api/stream.html#stream_readable_pipe_destination_options Temp file is not deleted on statusCode !== 200 fs.unlink() without a callback is deprecated (outputs warning) If dest file exists; it is overridden
下面是一个修改后的解决方案(使用ES6和promises),它可以处理这些问题。
const http = require("http");
const fs = require("fs");
function download(url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest, { flags: "wx" });
const request = http.get(url, response => {
if (response.statusCode === 200) {
response.pipe(file);
} else {
file.close();
fs.unlink(dest, () => {}); // Delete temp file
reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);
}
});
request.on("error", err => {
file.close();
fs.unlink(dest, () => {}); // Delete temp file
reject(err.message);
});
file.on("finish", () => {
resolve();
});
file.on("error", err => {
file.close();
if (err.code === "EEXIST") {
reject("File already exists");
} else {
fs.unlink(dest, () => {}); // Delete temp file
reject(err.message);
}
});
});
}
var fs = require('fs'),
request = require('request');
var download = function(uri, filename, callback){
request.head(uri, function(err, res, body){
console.log('content-type:', res.headers['content-type']);
console.log('content-length:', res.headers['content-length']);
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
});
};
download('https://www.cryptocompare.com/media/19684/doge.png', 'icons/taskks12.png', function(){
console.log('done');
});
你可以使用https://github.com/douzi8/ajax-request#download
request.download('http://res.m.ctrip.com/html5/Content/images/57.png',
function(err, res, body) {}
);