【发布时间】:2026-01-27 04:50:01
【问题描述】:
我最近在Nodejitsu 阅读了一篇博客,我想知道这段代码是如何工作的。
var fs = require('fs'),
http = require('http'),
httpProxy = require('../lib/node-http-proxy');
module.exports = function (logging) {
// Code here is run when the middleware is initially loaded.
var logFile = fs.createWriteStream('./requests.log');
return function (request, response, next) {
// Code here is run on each request.
if (logging) {
logFile.write(JSON.stringify(request.headers, true, 2));
}
next();
}
}
而对这段代码给出的解释是:
此中间件用于非常简单的日志记录 - 它将每个请求的标头写入日志文件。
上面导出的模块可以作为,
httpProxy.createServer(
require('./example-middleware')(true),
8000, 'localhost'
).listen(9000)
上述方法中带有next() 的代码是如何在每个请求中调用的?用法很简单: require 上面的模块,每次都会被调用。
【问题讨论】:
-
由于 Node 是单线程的,我想“next”只是设置了一个超时,以便在新请求进来时再次调用相同的函数。
-
@ChristopherHarris 不完全是。
next()告诉调用这个函数的人它已经完成并且应该调用中间件堆栈中的下一个函数。 -
@chasles,谢谢。听起来它仍然设置了一个超时来调用相同的函数。调用堆栈中的“相同”函数可能比之前建议的要高一点。
标签: javascript node.js