search

Home  >  Q&A  >  body text

node.js - nodejs request模块 如何流式下载文件

在http模块中 我chunk下载文件 然后创建文件夹把文件存在文件夹里

http.get(src,(res)=>{
    res.on('data',(chunk)=>{
        file += chunk;
    })
    
    res.on('end',()=>{
        var filep = Math.random();
        if(!fs.existsSync(filep)){ //每个文件创建一个文件夹
            var creats = fs.mkdirSync(filep);
            }
        fs.writeFile(filep+'a.mp4',file,(err)=>{
            if (err) throw err;
        });
    })
})

但在request模块里
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
这种方式 我无法创建文件夹 存储文件 我应当 如何在request 完成如上http模块类似的操作

高洛峰高洛峰2876 days ago441

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 15:58:42

    After trying it, it seems that the path to createWriteStream must exist and the folder will not be created. Or should I not put it in the pipe to create the folder? Generate it in advance

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 15:58:42

    Before creating the file, check if the folder exists and create it if it does not exist. Then make a request

    reply
    0
  • Cancelreply