使用fetch下载文件

    function consume(reader) {
        var getReader = reader.body.getReader();
        var total = 0;

        let fscreateFile = fs.createWriteStream('./src/fetchmusic1.wav')
        return new Promise((resolve, reject) => {
                    function pump() {
            getReader.read().then(({done, value}) => {
                if (done) {
                    resolve();
                    fscreateFile.end()
                    return ;
                }
                // 这里的value 是Uint8Array
               fscreateFile.write(Buffer.from(value))
               total += value.byteLength;
//            console.log(`下载字节 ${value.byteLength} bytes (${total} 总下载字节)`);
            pump();
        }).catch(reject)
        }
        pump();
    });
    }



            fetch('downfile/9043.wav')
                    .then(function(data){
                        consume(data);
                        return data;
                    })
                    .then((data) =>{
                console.log(data);
        })
        .catch((e) => {console.log("something went wrong: " + e)});

你可能感兴趣的:(使用fetch下载文件)