【发布时间】:2015-12-29 05:39:09
【问题描述】:
我试图了解闭包在 node.js 中是如何工作的
我有一个快速中间件,用于抓取远程站点 (*json) 的内容。这里的情况是我无法使用远程内容更新快速请求(我认为这是可能的)以在其他中间件中进一步处理它。
欢迎任何帮助:)
问候
const request = require('request');
const app = require('express')();
const base = { url: 'http://api.xxx', record: 'todo' };
function getFile(opts, cb) { // parse url using request
request({
url: opts.url,
headers: {
'User-Agent': 'request',
'Content-type': 'application/json'
}
}, function (error, response, body) {
if (error || response.statusCode != 200) {
cb(error);
} else {
var ret = {content: JSON.parse(body), request: opts}
cb(null, ret);
}
});
}
function grabData(req, res, next) {
console.log(new Date(), req.method, req.url);
getFile(base, function(err, data){
console.log(data.content); // WORKS OK!
//? How to get data.content injected in the request
// req.contents = data.content // not working
next();
});
}
// function calls ---------------------
app.use(grabData);
//app.use(furtherProcess) //? how to pass args here?
app.get('/', function(req,res){
res.send("> "+req.contents);
res.end();
});
app.listen(3000, function(){ console.log('Listen on port 3000...' ); });
【问题讨论】:
-
尝试使用 req.pipe ,所以可能是这样的: req.get(opt.url).pipe(res) ?
标签: javascript node.js asynchronous express