Node JS - SyntaxError:意外的令牌

时间:2018-03-23 13:35:38

标签: node.js

我试图找出为什么我会得到这个意外的令牌。

 Object.entries(sockets).forEach(([key, cs])) => {
     ^

SyntaxError: Unexpected token .
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3

Object.entries(套接字).forEach(([key,cs]))=> {

    process.stdout.write('\u001B[2J\u001B[0;0f'); //again clear node terminal
    const server = require('net').createServer(); // here use the createServer method from net module
    let counter = 0;
    let sockets = {};

    server.on('connection', socket => {
      socket.id = counter++; //everytime a client connects assign an id, and add to the counter for next socket Id

      //sockets[sockets.id] = socket;

      console.log('Client is connected!');
      socket.write('Hi, your name?\n');

      socket.on('data', data => {
        if(!socket[socket.id]) {
          socket.name = data.toString().trim();
          socket.write(`Welcome ... $[socket.name}!\n`);
          sockets[socket.id] = socket;
          return;
        }
       Object.entries(sockets).forEach(([key, cs])) => {
        if (socket.id == key)
          return;
        cs.write(`${socket.name}: `);
      //  console.log('data is', data);
        cs.write(data);
      });
    });

      socket.on('end', () => {
        delete sockets[socket.id];
        console.log('Client is now disconnected');
      });
    });

这是一个用节点编写的简单聊天程序,允许多个客户端相互连接和聊天。

1 个答案:

答案 0 :(得分:1)

你添加了一个额外的括号 Object.entries(sockets).forEach(([key, cs]) =>{})这一行。