サードパーティのライブラリを使用せずにNode.jsでファイルをダウンロードするにはどうすればよいですか?
特別なことは何も必要ありません。指定されたURLからファイルをダウンロードして、指定されたディレクトリに保存したいだけです。
サードパーティのライブラリを使用せずにNode.jsでファイルをダウンロードするにはどうすればよいですか?
特別なことは何も必要ありません。指定されたURLからファイルをダウンロードして、指定されたディレクトリに保存したいだけです。
HTTPリクエストを作成し、それを書き込み可能なファイルストリームにGET
パイプすることができます。response
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);
});
ターゲットファイルやディレクトリ、URLの指定など、コマンドラインでの情報収集をサポートする場合は、Commanderなどを確認してください。
エラーを処理することを忘れないでください!次のコードは、AugustoRomanの回答に基づいています。
var http = require('http');
var fs = require('fs');
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
});
}).on('error', function(err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (cb) cb(err.message);
});
};
Michelle Tilleyが言ったように、しかし適切な制御フローで:
var http = require('http');
var fs = require('fs');
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb);
});
});
}
イベントを待たずにfinish
、ナイーブなスクリプトが不完全なファイルになる可能性があります。
編集:明示的に呼び出されるのではなく、cb
に渡されるべきであると指摘してくれた@AugustoRomanに感謝します。file.close
エラーの処理について言えば、リクエストエラーをリッスンする方がさらに優れています。応答コードをチェックして検証することもできます。ここでは、200の応答コードでのみ成功と見なされますが、他のコードでもよい場合があります。
const fs = require('fs');
const http = require('http');
const download = (url, dest, cb) => {
const file = fs.createWriteStream(dest);
const request = http.get(url, (response) => {
// check if response is success
if (response.statusCode !== 200) {
return cb('Response status was ' + response.statusCode);
}
response.pipe(file);
});
// close() is async, call cb after close completes
file.on('finish', () => file.close(cb));
// check for request error too
request.on('error', (err) => {
fs.unlink(dest, () => cb(err.message)); // delete the (partial) file and then return the error
});
file.on('error', (err) => { // Handle errors
fs.unlink(dest, () => cb(err.message)); // delete the (partial) file and then return the error
});
};
このコードは比較的単純ですが、によってネイティブにサポートされていないさらに多くのプロトコル(hello HTTPS!)を処理するため、リクエストモジュールhttp
を使用することをお勧めします。
それは次のように行われます:
const fs = require('fs');
const request = require('request');
const download = (url, dest, cb) => {
const file = fs.createWriteStream(dest);
const sendReq = request.get(url);
// verify response code
sendReq.on('response', (response) => {
if (response.statusCode !== 200) {
return cb('Response status was ' + response.statusCode);
}
sendReq.pipe(file);
});
// close() is async, call cb after close completes
file.on('finish', () => file.close(cb));
// check for request errors
sendReq.on('error', (err) => {
fs.unlink(dest, () => cb(err.message)); // delete the (partial) file and then return the error
});
file.on('error', (err) => { // Handle errors
fs.unlink(dest, () => cb(err.message)); // delete the (partial) file and then return the error
});
};
編集:
で動作させるにはhttps
、変更します
const http = require('http');
に
const http = require('https');
gfxmonkの答えは、コールバックとfile.close()
完了の間に非常に厳しいデータ競合があります。 file.close()
実際には、クローズが完了したときに呼び出されるコールバックを受け取ります。そうしないと、ファイルの即時使用が失敗する可能性があります(非常にまれです!)。
完全な解決策は次のとおりです。
var http = require('http');
var fs = require('fs');
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function(response) {
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
});
});
}
終了イベントを待たずに、単純なスクリプトが不完全なファイルになる可能性があります。closeを介してコールバックをスケジュールしないcb
と、ファイルにアクセスしてからファイルが実際に準備できるまでの間に競合が発生する可能性があります。
node.jsが変更された可能性がありますが、他のソリューション(ノードv8.1.2を使用)にはいくつかの問題があるようです。
file.close()
する必要はありません。finish
デフォルトでfs.createWriteStream
は、はautoCloseに設定されています:https ://nodejs.org/api/fs.html#fs_fs_createwritestream_path_optionsfile.close()
エラー時に呼び出す必要があります。ファイルが削除されるときにこれは必要ないかもしれませんが(unlink()
)、通常は次のようになります:https ://nodejs.org/api/stream.html#stream_readable_pipe_destination_optionsstatusCode !== 200
fs.unlink()
コールバックなしは非推奨です(警告を出力します)dest
ファイルが存在する場合。オーバーライドされます以下は、これらの問題を処理する修正されたソリューション(ES6とpromiseを使用)です。
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);
}
});
});
}
es6スタイルのpromiseベースの方法を探しに来た人にとっては、次のようになると思います。
var http = require('http');
var fs = require('fs');
function pDownload(url, dest){
var file = fs.createWriteStream(dest);
return new Promise((resolve, reject) => {
var responseSent = false; // flag to make sure that response is sent only once.
http.get(url, response => {
response.pipe(file);
file.on('finish', () =>{
file.close(() => {
if(responseSent) return;
responseSent = true;
resolve();
});
});
}).on('error', err => {
if(responseSent) return;
responseSent = true;
reject(err);
});
});
}
//example
pDownload(url, fileLocation)
.then( ()=> console.log('downloaded file no issues...'))
.catch( e => console.error('error while downloading', e));
次のコードは、BrandonTilleyの回答に基づいています。
var http = require('http'),
fs = require('fs');
var request = http.get("http://example12345.com/yourfile.html", function(response) {
if (response.statusCode === 200) {
var file = fs.createWriteStream("copy.html");
response.pipe(file);
}
// Add timeout.
request.setTimeout(12000, function () {
request.abort();
});
});
エラーが発生したときにファイルを作成しないでください。タイムアウトを使用して、X秒後にリクエストを閉じることをお勧めします。
上記の他の回答といくつかの微妙な問題に基づいて、ここに私の試みがあります。
fs.access
。fs.createWriteStream
を取得した場合にのみ作成してください。これにより、一時ファイルハンドルを整理するために必要なコマンド200 OK
の量が減ります。fs.unlink
200 OK
いる可能性があります(ネットワーク呼び出しを行っているときに別のプロセスがファイルを作成したと想像してください)。reject
EEXIST
download
を取得した場合は、再帰的に呼び出します。301 Moved Permanently
302 Found (Moved Temporarily)
download
でした。このようにして、ネストされたPromiseのチェーンは正しい順序で解決されます。resolve(download)
download(...).then(() => resolve())
Promise
const https = require('https');
const fs = require('fs');
/**
* Download a resource from `url` to `dest`.
* @param {string} url - Valid URL to attempt download of resource
* @param {string} dest - Valid path to save the file.
* @returns {Promise<void>} - Returns asynchronously when successfully completed download
*/
function download(url, dest) {
return new Promise((resolve, reject) => {
// Check file does not exist yet before hitting network
fs.access(dest, fs.constants.F_OK, (err) => {
if (err === null) reject('File already exists');
const request = https.get(url, response => {
if (response.statusCode === 200) {
const file = fs.createWriteStream(dest, { flags: 'wx' });
file.on('finish', () => resolve());
file.on('error', err => {
file.close();
if (err.code === 'EEXIST') reject('File already exists');
else fs.unlink(dest, () => reject(err.message)); // Delete temp file
});
response.pipe(file);
} else if (response.statusCode === 302 || response.statusCode === 301) {
//Recursively follow redirects, only a 200 will resolve.
download(response.headers.location, dest).then(() => resolve());
} else {
reject(`Server responded with ${response.statusCode}: ${response.statusMessage}`);
}
});
request.on('error', err => {
reject(err.message);
});
});
});
}
こんにちは、 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コアを使用できます。
最新バージョン(ES6、Promise、Node 12.x +)はhttps/httpで動作します。また、リダイレクト302と301もサポートしています。標準のNode.jsライブラリで簡単に実行できるため、サードパーティのライブラリは使用しないことにしました。
// download.js
import fs from 'fs'
import https from 'https'
import http from 'http'
import { basename } from 'path'
import { URL } from 'url'
const TIMEOUT = 10000
function download (url, dest) {
const uri = new URL(url)
if (!dest) {
dest = basename(uri.pathname)
}
const pkg = url.toLowerCase().startsWith('https:') ? https : http
return new Promise((resolve, reject) => {
const request = pkg.get(uri.href).on('response', (res) => {
if (res.statusCode === 200) {
const file = fs.createWriteStream(dest, { flags: 'wx' })
res
.on('end', () => {
file.end()
// console.log(`${uri.pathname} downloaded to: ${path}`)
resolve()
})
.on('error', (err) => {
file.destroy()
fs.unlink(dest, () => reject(err))
}).pipe(file)
} else if (res.statusCode === 302 || res.statusCode === 301) {
// Recursively follow redirects, only a 200 will resolve.
download(res.headers.location, dest).then(() => resolve())
} else {
reject(new Error(`Download request failed, response status: ${res.statusCode} ${res.statusMessage}`))
}
})
request.setTimeout(TIMEOUT, function () {
request.abort()
reject(new Error(`Request timeout after ${TIMEOUT / 1000.0}s`))
})
})
}
export default download
私が修正した彼の要点についてAndreyTkachenkoに工藤
別のファイルに含めて使用する
const download = require('./download.js')
const url = 'https://raw.githubusercontent.com/replace-this-with-your-remote-file'
console.log('Downloading ' + url)
async function run() {
console.log('Downloading file')
try {
await download(url, 'server')
console.log('Download done')
} catch (e) {
console.log('Download failed')
console.log(e.message)
}
}
run()
Vince Yuanのコードは素晴らしいですが、何か問題があるようです。
function download(url, dest, callback) {
var file = fs.createWriteStream(dest);
var request = http.get(url, function (response) {
response.pipe(file);
file.on('finish', function () {
file.close(callback); // close() is async, call callback after close completes.
});
file.on('error', function (err) {
fs.unlink(dest); // Delete the file async. (But we don't check the result)
if (callback)
callback(err.message);
});
});
}
const download = (url, path) => new Promise((resolve, reject) => {
http.get(url, response => {
const statusCode = response.statusCode;
if (statusCode !== 200) {
return reject('Download error!');
}
const writeStream = fs.createWriteStream(path);
response.pipe(writeStream);
writeStream.on('error', () => reject('Error writing to file!'));
writeStream.on('finish', () => writeStream.close(resolve));
});}).catch(err => console.error(err));
httpとhttpsの両方を使用できるため、request()を使用することをお勧めします。
request('http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg')
.pipe(fs.createWriteStream('cat.jpg'))
✅したがって、パイプラインを使用すると、他のすべてのストリームが閉じられ、メモリリークがないことが確認されます。
実例:
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.'); } ); });
https://github.com/douzi8/ajax-request#downloadを使用できます
request.download('http://res.m.ctrip.com/html5/Content/images/57.png',
function(err, res, body) {}
);
読み取り可能なストリームを解決するpromiseを使用してダウンロードします。リダイレクトを処理するための追加のロジックを配置します。
var http = require('http');
var promise = require('bluebird');
var url = require('url');
var fs = require('fs');
var assert = require('assert');
function download(option) {
assert(option);
if (typeof option == 'string') {
option = url.parse(option);
}
return new promise(function(resolve, reject) {
var req = http.request(option, function(res) {
if (res.statusCode == 200) {
resolve(res);
} else {
if (res.statusCode === 301 && res.headers.location) {
resolve(download(res.headers.location));
} else {
reject(res.statusCode);
}
}
})
.on('error', function(e) {
reject(e);
})
.end();
});
}
download('http://localhost:8080/redirect')
.then(function(stream) {
try {
var writeStream = fs.createWriteStream('holyhigh.jpg');
stream.pipe(writeStream);
} catch(e) {
console.error(e);
}
});
http、https、およびrequestモジュールを使用して回答を見ました。httpまたはhttpsプロトコルのいずれかをサポートするさらに別のネイティブNodeJSモジュールを使用して1つ追加したいと思います。
私は公式のNodeJSAPIと、私が行っていることについてこの質問に対する他のいくつかの回答を参照しました。以下は、私がそれを試すために書いたテストであり、意図したとおりに機能しました。
import * as fs from 'fs';
import * as _path from 'path';
import * as http2 from 'http2';
/* ... */
async function download( host, query, destination )
{
return new Promise
(
( resolve, reject ) =>
{
// Connect to client:
const client = http2.connect( host );
client.on( 'error', error => reject( error ) );
// Prepare a write stream:
const fullPath = _path.join( fs.realPathSync( '.' ), destination );
const file = fs.createWriteStream( fullPath, { flags: "wx" } );
file.on( 'error', error => reject( error ) );
// Create a request:
const request = client.request( { [':path']: query } );
// On initial response handle non-success (!== 200) status error:
request.on
(
'response',
( headers/*, flags*/ ) =>
{
if( headers[':status'] !== 200 )
{
file.close();
fs.unlink( fullPath, () => {} );
reject( new Error( `Server responded with ${headers[':status']}` ) );
}
}
);
// Set encoding for the payload:
request.setEncoding( 'utf8' );
// Write the payload to file:
request.on( 'data', chunk => file.write( chunk ) );
// Handle ending the request
request.on
(
'end',
() =>
{
file.close();
client.close();
resolve( { result: true } );
}
);
/*
You can use request.setTimeout( 12000, () => {} ) for aborting
after period of inactivity
*/
// Fire off [flush] the request:
request.end();
}
);
}
次に、たとえば:
/* ... */
let downloaded = await download( 'https://gitlab.com', '/api/v4/...', 'tmp/tmpFile' );
if( downloaded.result )
{
// Success!
}
// ...
外部参照
情報の編集
function
用に作成されましたが、これに注意しないと、貢献者がすぐに追加した宣言を適切に使用しないと、推定されるjavascriptユーザーに対してソリューションが機能しませんでした。ありがとう!download.js(つまり、/project/utils/download.js)
const fs = require('fs');
const request = require('request');
const download = (uri, filename, callback) => {
request.head(uri, (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);
});
};
module.exports = { download };
app.js
...
// part of imports
const { download } = require('./utils/download');
...
// add this function wherever
download('https://imageurl.com', 'imagename.jpg', () => {
console.log('done')
});
エクスプレスを使用している場合は、res.download()メソッドを使用します。それ以外の場合は、fsモジュールを使用します。
app.get('/read-android', function(req, res) {
var file = "/home/sony/Documents/docs/Android.apk";
res.download(file)
});
(また)
function readApp(req,res) {
var file = req.fileName,
filePath = "/home/sony/Documents/docs/";
fs.exists(filePath, function(exists){
if (exists) {
res.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition" : "attachment; filename=" + file});
fs.createReadStream(filePath + file).pipe(res);
} else {
res.writeHead(400, {"Content-Type": "text/plain"});
res.end("ERROR File does NOT Exists.ipa");
}
});
}
パス:imgタイプ:jpgランダムuniqid
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;
}
ライブラリがないと、指摘するだけでもバグが発生する可能性があります。ここにいくつかあります:
Protocol "https:" not supported.
ここに私の提案:
wget
またはのようなシステムツールを呼び出すcurl
var wget = require('node-wget-promise');
wget('http://nodejs.org/images/logo.svg');
既存のものが私の要件に合わなかったので、私自身のソリューションを書く。
これがカバーするもの:
http
ます)それはタイプされた、それはより安全です。プレーンJS(フローなし、TSなし)で作業している場合、または.d.ts
ファイルに変換する場合は、自由にタイプを削除してください
index.js
import httpsDownload from httpsDownload;
httpsDownload('https://example.com/file.zip', './');
httpsDownload。[js|ts]
import https from "https";
import fs from "fs";
import path from "path";
function download(
url: string,
folder?: string,
filename?: string
): Promise<void> {
return new Promise((resolve, reject) => {
const req = https
.request(url, { headers: { "User-Agent": "javascript" } }, (response) => {
if (response.statusCode === 302 && response.headers.location != null) {
download(
buildNextUrl(url, response.headers.location),
folder,
filename
)
.then(resolve)
.catch(reject);
return;
}
const file = fs.createWriteStream(
buildDestinationPath(url, folder, filename)
);
response.pipe(file);
file.on("finish", () => {
file.close();
resolve();
});
})
.on("error", reject);
req.end();
});
}
function buildNextUrl(current: string, next: string) {
const isNextUrlAbsolute = RegExp("^(?:[a-z]+:)?//").test(next);
if (isNextUrlAbsolute) {
return next;
} else {
const currentURL = new URL(current);
const fullHost = `${currentURL.protocol}//${currentURL.hostname}${
currentURL.port ? ":" + currentURL.port : ""
}`;
return `${fullHost}${next}`;
}
}
function buildDestinationPath(url: string, folder?: string, filename?: string) {
return path.join(folder ?? "./", filename ?? generateFilenameFromPath(url));
}
function generateFilenameFromPath(url: string): string {
const urlParts = url.split("/");
return urlParts[urlParts.length - 1] ?? "";
}
export default download;
function download(url, dest, cb) {
var request = http.get(url, function (response) {
const settings = {
flags: 'w',
encoding: 'utf8',
fd: null,
mode: 0o666,
autoClose: true
};
// response.pipe(fs.createWriteStream(dest, settings));
var file = fs.createWriteStream(dest, settings);
response.pipe(file);
file.on('finish', function () {
let okMsg = {
text: `File downloaded successfully`
}
cb(okMsg);
file.end();
});
}).on('error', function (err) { // Handle errors
fs.unlink(dest); // Delete the file async. (But we don't check the result)
let errorMsg = {
text: `Error in file downloadin: ${err.message}`
}
if (cb) cb(errorMsg);
});
};
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');
});
サードパーティに依存せずにリダイレクトを検索する別の方法を次に示します。
var download = function(url, dest, cb) {
var file = fs.createWriteStream(dest);
https.get(url, function(response) {
if ([301,302].indexOf(response.statusCode) !== -1) {
body = [];
download(response.headers.location, dest, cb);
}
response.pipe(file);
file.on('finish', function() {
file.close(cb); // close() is async, call cb after close completes.
});
});
}
res.redirect
httpsファイルのダウンロードURLを使用してみると、ファイルがダウンロードされます。
好き:res.redirect('https//static.file.com/file.txt');
特にPDFやその他のランダムなファイルに関しては、このアプローチが最も役立つことがわかりました。
import fs from "fs";
fs.appendFile("output_file_name.ext", fileDataInBytes, (err) => {
if (err) throw err;
console.log("File saved!");
});
次のように使用することをお勧めしますres.download
。
app.get('/download', function(req, res){
const file = `${__dirname}/folder/abc.csv`;
res.download(file); // Set disposition and send it.
});
var requestModule=require("request");
requestModule(filePath).pipe(fs.createWriteStream('abc.zip'));