要在Node.js中使用curl下载文件,您需要使用Node的child_process模块。你必须使用child_process的spawn方法调用curl。为了方便,我使用spawn而不是exec - spawn返回一个包含数据事件的流,并且不像exec那样有缓冲区大小问题。这并不意味着执行力不如产卵;实际上我们将使用exec来使用wget下载文件。
// Function to download file using curl
var download_file_curl = function(file_url) {
// extract the file name
var file_name = url.parse(file_url).pathname.split('/').pop();
// create an instance of writable stream
var file = fs.createWriteStream(DOWNLOAD_DIR + file_name);
// execute curl using child_process' spawn function
var curl = spawn('curl', [file_url]);
// add a 'data' event listener for the spawn instance
curl.stdout.on('data', function(data) { file.write(data); });
// add an 'end' event listener to close the writeable stream
curl.stdout.on('end', function(data) {
file.end();
console.log(file_name + ' downloaded to ' + DOWNLOAD_DIR);
});
// when the spawn child process exits, check if there were any errors and close the writeable stream
curl.on('exit', function(code) {
if (code != 0) {
console.log('Failed: ' + code);
}
});
};
完美的片断语法。我将所有图像下载到本地文件夹中。 – Kirankamana
很高兴知道! :) – AdityaParab