[英]How to download audio file from URL in Node.js?
How to download audio file from URL and store it in local directory?如何从 URL 下载音频文件并将其存储在本地目录中? I'm using Node.js and I tried the following code:
我正在使用 Node.js 并尝试了以下代码:
var http = require('http');
var fs = require('fs');
var dest = 'C./test'
var url= 'http://static1.grsites.com/archive/sounds/comic/comic002.wav'
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);
});
});
}
No error occured but the file has not been found.未发生错误,但未找到该文件。
Duplicate of How to download a file with Node.js (without using third-party libraries)?重复如何使用 Node.js 下载文件(不使用第三方库)? , but here is the code specific to your question:
,但这里是特定于您的问题的代码:
var http = require('http');
var fs = require('fs');
var file = fs.createWriteStream("file.wav");
var request = http.get("http://static1.grsites.com/archive/sounds/comic/comic002.wav", function(response) {
response.pipe(file);
});
Your code is actually fine, you just don't call the download function.你的代码实际上很好,你只是不调用下载函数。 Try adding this to the end :
尝试将其添加到最后:
download(url, dest, function(err){
if(err){
console.error(err);
}else{
console.log("Download complete");
}
});
Also, change the value of dest
to something else, like just "test.wav"
or something.此外,将
dest
的值更改为其他内容,例如"test.wav"
或其他内容。 'C./test'
is a bad path. 'C./test'
是一条糟糕的道路。
I tried it on my machine and your code works fine just adding the call and changing dest
.我在我的机器上试过了,你的代码工作正常,只需添加调用并更改
dest
。
Here is an example using Axios with an API that may require authorization这是一个将 Axios 与可能需要授权的 API 一起使用的示例
const Fs = require('fs'); const Path = require('path'); const Axios = require('axios'); async function download(url) { let filename = "filename"; const username = "user"; const password = "password" const key = Buffer.from(username + ':' + password).toString("base64"); const path = Path.resolve(__dirname, "audio", filename) const response = await Axios({ method: 'GET', url: url, responseType: 'stream', headers: { 'Authorization': 'Basic ' + key } }) response.data.pipe(Fs.createWriteStream(path)) return new Promise((resolve, reject) => { response.data.on('end', () => { resolve(); }) response.data.on('error', () => { reject(err); }) }) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.