如何从URL下载音频文件并将其存储在本地目录中? 我使用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);
});
});
}
未发生错误但未找到该文件。
答案 0 :(得分:0)
How to download a file with Node.js (without using third-party libraries)?的重复,但以下是您特定问题的代码:
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);
});
答案 1 :(得分:0)
您的代码实际上很好,您只是不要调用下载功能。尝试将其添加到最后:
download(url, dest, function(err){
if(err){
console.error(err);
}else{
console.log("Download complete");
}
});
另外,将dest
的值更改为其他内容,例如"test.wav"
或其他内容。 'C./test'
是一条糟糕的道路。
我在我的计算机上尝试过,只需添加通话并更改dest
,您的代码就可以正常工作。
答案 2 :(得分:0)
这是一个使用 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);
})
})
}