NodeJS中的全局变量

时间:2018-10-12 12:00:50

标签: node.js

我有两个NodeJS文件:

main.js:

global.clients = [];

const net       = require('net');
const ki        = require('./keyboard_interface.js');

net.createServer(function (socket)
{
    // Put this new client in the list
    clients.push(socket);
});

keyboard_interface.js:

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.on('line', function(line)
{
        if (line == 'c')
        {
                console.log('----Connected Clients----');
                clients.forEach(function (socket)
                {
                            console.log(socket.name);
                });
        }
});

我已经验证了clients数组中是否填充了内容,我可以从keyboard_interface.js访问clients变量,但是为什么它为空?

1 个答案:

答案 0 :(得分:0)

使用global.clients访问keyboard_interface.js中的数组