Welcome to ZaiNaLe Developer Community-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
933 views
in Technique[技术] by (71.8m points)

怎么取到 node 里 on 绑定的回调的返回值

let axios = require('axios');
let iconv = require('iconv-lite');

axios({
    url : 'xxxxx/gbk.html',
    responseType : 'stream' //将数据转化为流返回
})
.then(res=>{
    //此时的res.data 则为stream
    let chunks = [];
    res.data.on('data',chunk=>{
        chunks.push(chunk);
    });
    res.data.on('end',()=>{
        let buffer = Buffer.concat(chunks);
        //通过iconv来进行转化。
        let str = iconv.decode(buffer,'gbk');
        console.log(str);
        // 想将 str 返回出去
    })
})
// 在这里接收 str
const res = await axios()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

包装个 Promise 不就好了?

axios({
    url : 'xxxxx/gbk.html',
    responseType : 'stream' // 将数据转化为流返回
})
.then(res => {
    return new Promise((resolve, reject) => {
        // 此时的res.data 则为stream
        let chunks = [];
        res.data.on('data',chunk=>{
            chunks.push(chunk);
        });
        res.data.on('end',()=>{
            let buffer = Buffer.concat(chunks);
            // 通过iconv来进行转化。
            let str = iconv.decode(buffer,'gbk');
            // 将 str 返回出去
            resolve(str);
        });
    });
})

// 在这里接收 str
const res = await axios();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to ZaiNaLe Developer Community-Open, Learning and Share
...