request之进度监听

2021-11-05  本文已影响0人  studentliubo

直接上代码:

const request = require('request');

const url = ''; // 资源地址

let receivedBytes = 0;
let totalBytes = 0;

const req = request({
    method: 'GET',
    uri: url
  });

req.on('response', (data) => {
    // 更新总文件字节大小
    totalBytes = parseInt(data.headers['content-length'], 10);
  });

req.on('data', (chunk) => {
    // 更新下载的文件块字节大小
    receivedBytes += chunk.length;
    console.log("receivedBytes, totalBytes: ", receivedBytes, totalBytes);
});

req.on('end', () => {
    console.log('下载完成');
});

事件类型的来源文档

中阶示例

边读边写,控制读取可写入的速度,读取30b的文件,每次只能读5b,每次只能写入1b

function pipe(readFile,writeFileu){
    let rs = fs.createReadStream(readFile,{
        highWaterMark:5
    })
    let ws = fs.createWriteStream(writeFileu,{
        highWaterMark:1
    })
    rs.on('data',function(chunk){
        console.log('读取')
        // 当ws.write() 返回false时,表示没有空间继续写入了,暂停读取
        if(ws.write(chunk) == false){
            rs.pause() // 暂停rs的data事件
        }
    })
    // 当触发可写流的drain,表示有空间继续写入了,继续读取文件
    ws.on('drain',function(){
        rs.resume() // 恢复rs的data事件  把当前读入的内容都写到文件中了,继续调用读写
    })
    // 当读取流触发end方法,表示读取完毕,这时关闭可写流的写入
    rs.on('end',function(){
        ws.end()
    })
}
上一篇 下一篇

猜你喜欢

热点阅读