У меня есть это (полный код - ну вроде):
const fs = require('fs');
const http = require('http');
const url = require('url');
const path = require('path');
const Handlebars = require('handlebars');
const Router = require('./router');
const Utils = require('./utils');
const utils = new Utils();
const views = require('./views');
let hostname,
server,
router = new Router();
const port = ( process.argv.length > 2 ) ? parseInt(process.argv[process.argv.length - 1]) : 3000;
function install ( config ) {
let install_processes = [
installControllers( config ),
installModels( config ),
views( config )
];
return Promise.all( install_processes );
}
function installControllers ( config ) {
// To keep example compact, this return a Promise
}
function installModels ( config ) {
// To keep example compact, this return a Promise
}
function handleRequest ( req, res ) {
let r = global.routes.find( ( obj ) => obj.route === req.url );
if ( r ) {
let template = global.routes.views.layout,
output = template( req.body );
r.action();
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end( output );
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end("404: page not found, " + req.url);
}
}
var fw = (function ( ƒ ) {
ƒ.init = function Init ( config ) {
config = config;
hostname = config.hostname ? config.hostname : '127.0.0.1';
install( config )
.then(function () {
ƒ.startServer();
})
.catch(function ( err ) {
console.error("Error", err);
})
}
ƒ.startServer = function () {
server = http.createServer( handleRequest ).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}`);
});
}
return ƒ;
}( fw || {} ));
module.exports = fw;
Обратите внимание, что переменные и обработчики установлены в другом месте.
Все отлично работает. Но почему обработчик handleRequest
вызывается каждую секунду (без каких-либо входящих запросов. И он фактически называется ДВАЖДЫ в течение этой секунды)? Если я добавлю console.log, он будет выводить каждую секунду или около того.
Я ожидаю, что он будет вызываться ТОЛЬКО при фактических запросах к серверу. Это какой-то обработчик тайм-аута, который работает в фоновом режиме или тому подобное?