如何在nodejs中使用npm请求下载音频文件



我有这段代码给我一些原始数据

requestPromisePost(options) {
return new Promise((resolve, reject) => {
request(options, function (error, response,dfdf) {
if (error) return reject(error);
return resolve(response.body);
});
});
}

const auth = new Buffer('apiKey' + ':' + '').toString('base64');
const options = {
'method': 'GET',
'url': 'myUrl',
'headers': {
'Content-Type': 'application/json',
'Authorization': `Basic ${auth}`
}
}
const result = await this.requestPromisePost(options);
console.log(result)

给出了这些数据

��Y�;��;��n' +
'�x01��b�H�x13ZP�H��t�r�x17(x1C`��BR�6q��A|��m�O���l�x0Fr��@��x15!r�X���x05�A�K:6(ӻ���ܖ&�6r�[[_�?x7FpHH�Dr��q��x18%2x0B�x14�@x01x03x12�;�x04yB` x01Jʠfb�btQt;U�m~;x17m�FHlq�ąrΑ|J����B��x17�~�X��x1Ax16f��W�x0E/x17y&}J�4

是一个音频文件。我得下载文件。请帮助。

解决方案

const filename = "myAudio.mp3"
const options = {
'method': 'GET',
'url': YOUR_AUDIO_URL_HERE,
'headers': {
'Content-Type': 'application/json',
},
encoding: null // <-- This is so important! It means binary data.
}
request(options, function (err, resp, data) {
// Here, data is the argument which contains binary data of the file.
if (err || resp.statusCode != 200) {
console.log(err, resp.body);
} else {
try {
fs.writeFileSync(filename, data, { encoding: 'binary'});
console.log(`Output audio file: ${filename}, length: ${data.length} byte(s)`);
} catch (e) {
console.log(e.message);
}
}
});

相关内容

  • 没有找到相关文章