我有一个NodeJS项目,需要在另一个文件中我的app.js文件中定义的变量之一,这可能吗?
我的代码
app.js
var app = express();
var io = require('socket.io').listen(app);
...
otherFile.js
var models = require('../models');
var express = require('express');
var path = require('path');
var fs = require("fs"); //To-Delete
var recursive = require('recursive-readdir');
var router = express.Router();
var app = require ('../app.js');
// creating a new websocket to keep the content updated without any AJAX request
app.io.sockets.on('connection', function(socket) {
fs.watchFile(__dirname + '../README.md', function(curr, prev) {
// on file change we can read the new xml
fs.readFile(__dirname + '../README.md', function(err, data) {
if (err) throw err;
// parsing the new xml data and converting them into json file
// var json = parser.toJson(data);
// send the new data to the client
socket.volatile.emit('notification', {message: 'el archivo cambio'});
});
});
});
我遇到的错误是TypeError: Cannot read property 'sockets' of undefined
块引用
答案 0 :(得分:4)
当你这样做时:
var io = require('socket.io').listen(app);
您只需创建一个局部变量,该变量仅在该文件的范围内可见。
如果您想在导入app.io
后使用app
从其他文件访问该文件,则需要:
添加io
作为您应用的属性:
app.io = io;
或简单地将两者结合起来:
app.io = require('socket.io').listen(app);
答案 1 :(得分:2)
来自socket.io docs这应该有效:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.sockets.on('connection', function(socket) {
// ... your code
});