2017-07-19 93 views
0

可以说我有以下文件的NodeJS:包括的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

简单的解决办法是使用fs.readFile[Sync]阅读代码,并把它传递给evalio.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')); 
}); 
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(); 
});