假设我有以下NodeJS文件:
var https = require("https");
var express = require("express");
var app = express();
var options = {};
var serverPort = 8443;
var server = https.createServer(options, app);
var io = require('socket.io')(server);
var numUsers = 0;
app.get('/', function(req, res){
res.sendFile('/home/domain/index.php');
});
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
});
server.listen(serverPort, function(){
console.log("\n--------------------------------");
console.log('Node HTTPs Server');
console.log('Currently Listening on port %d',serverPort);
console.log("--------------------------------");
});
由于我无法在服务器上获取SNI to work,因此我必须采用老式的方式为每个子域编写脚本。但我想要做的是让io.on('connection', function(socket) {}
区域内的函数为included
。因此不包括像类或类似的东西,但从字面上看,代码只是从另一个文件中获取并进行处理,就好像它已经存在于该文件中一样。很像PHP确实包括。这可能吗?
答案 0 :(得分:0)
最简单的解决方案是使用fs.readFile[Sync]
读取代码并将其传递给eval
内的io.on('connection', function(socket) {})
io.on('connection', function(socket){
socket.on('user-login', function(data){
++numUsers;
});
socket.on('new message', function (msg,room) {
console.log(msg);
});
socket.on("disconnect", function() {
--numUsers;
});
// eval function loaded outside io.on('connection')
eval(someFunctionBody);
// or
eval(fs.readFileSync('path/to/function/body.js'));
});
答案 1 :(得分:0)
你不能只使用require
吗?
<强> functions.js 强>
function myFunc() {
console.log("I am a funky func");
}
module.exports = {
myFunc,
myOtherFunc,
};
<强> index.js 强>
var https = require("https");
var express = require("express");
// snip
var funcs = require('./functions');
io.on('connection', function(socket){
// snip
funcs.myFunc();
});