我使用Node.js request模块发出http请求,并希望将响应传递给某些流。这是两个代码片段:
正常运作的示例。我只是管道来自response
事件的回复。
const fs = require('fs')
const path = require('path')
const request = require('request')
const filepath = path.resolve('./tmp.zip')
const ws = fs.createWriteStream(filepath)
function get() {
return new Promise((resolve, reject) => {
request.get(uri, options)
.on('response', (res) => {
ws.on('finish', () => console.log('finish'))
res.pipe(ws)
resolve()
})
.on('error', (err) => {
reject(err)
})
})
}
get().then(() => {
console.log('done')
}).catch((err) => console.log(err))
效果不正常。我在promise resolve
回调中将响应传递给then
回调一个promise和pipe。从第一种正常工作的方法来看,这种方法的文件大小更加平静。
const fs = require('fs')
const path = require('path')
const request = require('request')
const filepath = path.resolve('./tmp.zip')
const ws = fs.createWriteStream(filepath)
function get() {
return new Promise((resolve, reject) => {
request.get(uri, options)
.on('response', (res) => {
resolve(res)
})
.on('error', (err) => {
reject(err)
})
})
}
get().then((res) => {
ws.on('finish', () => console.log('finish'))
res.pipe(ws)
}).catch((err) => console.log(err))
请告诉我为什么第二个例子也不能正常工作?
答案 0 :(得分:0)
这很奇怪。我使用http模块而不是请求...
const fs = require('fs');
const path = require('path');
const http = require('http');
const filepath = path.resolve('./index.html');
const ws = fs.createWriteStream(filepath);
const options = {
hostname: "your_url",
port: "80",
path: "/index.html"
};
function get() {
return new Promise((resolve, reject) => {
http.get(uri, function(res) {
resolve(res);
});
});
}
get().then(function(res) {
console.log('then');
ws.on('finish', () => {
console.log('finish');
})
res.pipe(ws);
}).catch((err) => console.log(err));