如何在不使用第三方库的情况下使用Node.js下载文件?
我不需要什么特别的东西。我只想从给定的URL下载文件,然后将其保存到给定的目录。
如何在不使用第三方库的情况下使用Node.js下载文件?
我不需要什么特别的东西。我只想从给定的URL下载文件,然后将其保存到给定的目录。
当前回答
路径:img 类型:JPG 随机函数
function resim(url) {
var http = require("http");
var fs = require("fs");
var sayi = Math.floor(Math.random()*10000000000);
var uzanti = ".jpg";
var file = fs.createWriteStream("img/"+sayi+uzanti);
var request = http.get(url, function(response) {
response.pipe(file);
});
return sayi+uzanti;
}
其他回答
✅So if you use pipeline, it would close all other streams and make sure that there are no memory leaks. Working example: const http = require('http'); const { pipeline } = require('stream'); const fs = require('fs'); const file = fs.createWriteStream('./file.jpg'); http.get('http://via.placeholder.com/150/92c952', response => { pipeline( response, file, err => { if (err) console.error('Pipeline failed.', err); else console.log('Pipeline succeeded.'); } ); });
从我的回答“在流上。pipe和。pipeline之间有什么区别”。
你好,我认为你可以使用child_process模块和curl命令。
const cp = require('child_process');
let download = async function(uri, filename){
let command = `curl -o ${filename} '${uri}'`;
let result = cp.execSync(command);
};
async function test() {
await download('http://zhangwenning.top/20181221001417.png', './20181221001417.png')
}
test()
另外,当你想下载较大、多个文件时,你可以使用集群模块来使用更多的cpu内核。
你可以使用https://github.com/douzi8/ajax-request#download
request.download('http://res.m.ctrip.com/html5/Content/images/57.png',
function(err, res, body) {}
);
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');
});
2022年底编辑:
Node v18及以上版本自带自带的Fetch API支持。使用它。
最初的回答:
对于支持承诺的节点,与其他答案相比,一个简单的(部分)Fetch API的Node shim只需要少量额外的代码:
const fs = require(`fs`);
const http = require(`http`);
const https = require(`https`);
module.exports = function fetch(url) {
return new Promise((resolve, reject) => {
const data = [];
const client = url.startsWith("https") ? https : http;
client
.request(url, (res) => {
res.on(`data`, (chunk) => data.push(chunk));
res.on(`end`, () => {
const asBytes = Buffer.concat(data);
const asString = asBytes.toString(`utf8`);
resolve({
arrayBuffer: async () => asBytes,
json: async () => JSON.parse(asString),
text: async () => asString,
});
});
res.on(`error`, (e) => reject(e));
})
.end();
});
};
你可以用它来做任何你需要的事情,使用普通的fetch语法:
const fetch = require(`./tiny-fetch.js`);
fetch(`https://placekitten.com/200/300`)
.then(res => res.arrayBuffer())
.then(bytes => fs.writeFileSync(`kitten.jpg`, bytes))
.catch(e => console.error(e));
fetch(`https://jsonplaceholder.typicode.com/todos/1`)
.then(res => res.json())
.then(obj => console.log(obj))
.catch(e => console.error(e));
// etc.