请求节点模块:https://github.com/request/request有一个示例,它只获取响应,然后将其传送到可写文件流中。如果我有一个可变文件名怎么办?例如,如果链接可能是png或jpg?我收到回复后如何管道?
request.get('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
例如,
request.get(fileURL)
.on('response', res => {
let resType = res.headers['content-type'];
//get the file name based on the content-type
})
.pipe(fs.createWriteStream(fileName); //should use the fileName created in the on('response') callback
答案 0 :(得分:3)
你真的很亲密。你只需要在回调中输入管道:
let req = request.get(fileURL)
.on('response', res => {
let resType = res.headers['content-type'];
let fileName = figureOutExtension(resType); //get the file name based on the content-type
req.pipe(fs.createWriteStream(fileName));
})
答案 1 :(得分:0)
你应该在回调中创建文件,因为回调是在这个程序的末尾运行的,文件名是基于resType的。