Node.js 如何使用request nodejs模块创建变量文件名?
请求节点模块:有一个示例,它只获取响应,然后通过管道将其传输到可写文件流中。如果我有一个可变的文件名呢?例如,如果链接可以是png或jpg?在我得到回应后,我该如何管道Node.js 如何使用request nodejs模块创建变量文件名?,node.js,request,pipe,response,filenames,Node.js,Request,Pipe,Response,Filenames,请求节点模块:有一个示例,它只获取响应,然后通过管道将其传输到可写文件流中。如果我有一个可变的文件名呢?例如,如果链接可以是png或jpg?在我得到回应后,我该如何管道 request.get('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) 比如说, request.get(fileURL) .on('response', res => { let resType = r
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
你真的很接近。您只需在回调中插入管道:
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));
})
你真的很接近。您只需在回调中插入管道:
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));
})
您应该在回调中创建文件,因为回调在此程序结束时运行,文件名基于resType。您应该在回调中创建文件,因为回调在此程序结束时运行,文件名基于resType