我遇到了nodeJS导出理解问题......我将解释这个问题:
我试图将我/ bin / www文件中的变量导出到我的index.js文件中:
/ bin中/万维网
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('chat:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = require('socket.io')(http).listen(server);
module.exports.io = io;
console.log("FROM WWW FILE: " + exports.io);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
我试图在index.js中获取该变量:
index.js
var express = require('express');
var router = express.Router();
var www = require('../bin/www');
console.log("FROM INDEX.JS WWW OBJECT:" + www);
console.log("WWW.IO VARIABLE FROM INDEX.JS:" + www.io); //UNDEFINED ?
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
//io.on('connection', function (socket) {
// console.log("CONEXION ESTABLECIDA");
//socket.emit('news', { hello: 'world' });
//socket.on('my other event', function (data) {
// console.log(data.my);
//});
//});
module.exports = router;
console.log("IO IS:" + www.io); //UNDEFINED ?
我不确定为什么www.io未定义,我确定非常明显,但无法理解......
如果你能伸出援助之手我会很感激。
非常感谢!