簡體   English   中英

如何在nodejs中使用npm請求下載音頻文件

[英]How can I download audio file using npm request in nodejs

我有這段代碼,它給了我一些原始數據

        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�\x0F\r��@��\x15!r�X���\x05�A�K:6(ӻ���ܖ&�6r�[[_�?\x7FpHH�Dr��q��\x18%2\x0B�\x14�@\x01\x03\x12�;�\x04yB` \x01Jʠfb�\b\tQ\t;U�m~;\x17m�FHlq�ą\rΑ|J����B��\x17�~�X��\x1A\x16f��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);
        }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM