导入/导出模块和全局定义的变量

时间:2017-11-18 20:38:11

标签: javascript node.js

(注意,我正在使用Node.js创建一个telnet服务器并处理用户输入) 我在其他脚本中的函数内的javascript中使用变量/数组时遇到问题。

让我举一个更简单的例子:

var connections = []

是我的main.js中的数组 Broadcast.js是我放在一个单独模块中的函数,并尝试在main.js中使用broadcast()函数。

我得到的错误是声明连接未定义。如何让Broadcast.js能够在main.js中看到connections数组 ~~

例如在我的main.js中,我设置了一个数组来处理连接服务器的客户端

//point to Telnet library
const Telnet = require('ranvier-telnet');
const logger = require('./logger.js')
var outspeak = []
var connections = []
var clients = []






let server = new Telnet.TelnetServer(rawSocket => {

let telnetSocket = new Telnet.TelnetSocket();
//attaching socket
telnetSocket.attach(rawSocket);
//setting telnet options
telnetSocket.telnetCommand(Telnet.Sequences.WILL, Telnet.Options.OPT_EOR);
//giving clients a name
telnetSocket.name = rawSocket.remoteAddress + ":" + rawSocket.remotePort
//pushing client names to array
clients.push(telnetSocket.name);
//pushing client connections to an array
connections.push(rawSocket);
console.log(`${telnetSocket.name} has connected`)
logger(`${telnetSocket.name} has connected`)
broadcast(telnetSocket.name + " connected.")


telnetSocket.on('data', function (data) {
    //broadcast (telnetSocket.name + ">" + data, telnetSocket);
}

function broadcast (message, sender) {
    connections.forEach(function (connection) {
        //don't want to send it to sender
        if (connection === sender) return;
    connection.write(`${message} \n`);
    });

}

现在在我的主脚本中,只要我在main.js文件中键入函数,我就可以调用该数组/ push到该数组,从该数组中读取。

它可以轻松使用广播功能。

现在我想让它更进步,并在main.js上减少我的线条

但是一旦我将广播功能分成它自己的模块。

use strict'
//broadcast function

    function broadcast (message, sender) {
        connections.forEach(function (connection) {
            //don't want to send it to sender
            if (connection === sender) return;
        connection.write(`${message} \n`);
        });

    }

module.exports = broadcast

每当我尝试调用该广播函数时,我都会收到连接未定义的错误。这就像broadcast.js函数无法看到我的全局变量/数组。

这就是我调用它的方式

    // handle input
    telnetSocket.on('data', function (data) {
    broadcast (telnetSocket.name + ">" + data, telnetSocket);
    });

是的,const broadcast = require('./ broadcast.js');已被添加到顶部的文件中。

这是完整的代码:

'use strict'
//point to Telnet library
const Telnet = require('ranvier-telnet');
const logger = require('./logger.js');
const broadcast = require('./broadcast.js');
var connections = []
var clients = []




//had to call message as global variable


//Asan's timestamp functionm
//telnetstuff


console.log("Starting..."); 





let server = new Telnet.TelnetServer(rawSocket => {

    let telnetSocket = new Telnet.TelnetSocket();
    //attaching socket
    telnetSocket.attach(rawSocket);
    //setting telnet options
    telnetSocket.telnetCommand(Telnet.Sequences.WILL, Telnet.Options.OPT_EOR);
    //giving clients a name
    telnetSocket.name = rawSocket.remoteAddress + ":" + rawSocket.remotePort
    //pushing client names to array
    clients.push(telnetSocket.name);
    //pushing client connections to an array
    connections.push(rawSocket);
    console.log(`${telnetSocket.name} has connected`)
    logger(`${telnetSocket.name} has connected`)
    broadcast(telnetSocket.name + " connected.")


    // handle input
    telnetSocket.on('data', function (data) {
    broadcast (telnetSocket.name + ">" + data, telnetSocket);
    });

//removing client/connection from array
rawSocket.on('end', function () {
        clients.splice(clients.indexOf(telnetSocket), 1);
        connections.splice(connections.indexOf(rawSocket), 1);
        broadcast(telnetSocket.name + " has left.\n");
        logger(telnetSocket.name + " has left.");
        console.log(telnetSocket.name + " has left.");
    });


}).netServer


server.listen(4000);

console.log('ServerRunning...');
logger('>Server started.');

我在这里缺少什么?另外我提前道歉这是我提出的第一个问题,我今天能够尽可能多地了解如何提出问题,也许我没有使用正确的术语/术语?任何帮助都是值得赞赏的。

refactor\broadcast.js:5
                connections.forEach(function (connection) {
                ^

ReferenceError: connections is not defined

1 个答案:

答案 0 :(得分:0)

在nodejs中,当您声明一个不在任何函数定义中的变量时,它仅限于该文件的范围。 (这与浏览器javascript不同。)如果您想从外部访问某些内容,则需要将其导出:

module.exports.connections = connections;

然后将其导入另一个文件:

const connections = require(myFile);

只要您不尝试在任一文件中设置变量的值,这将起作用,但如果您这样做,它们最终将指向单独的对象。但是改变它,在它上面调用方法等应该可以正常工作。