NODEJS + WS LIBRARY = BUFFER ALLOC ERROR

时间:2018-05-23 19:00:59

标签: node.js express websocket buffer

我们正在构建一个简单的express + websocket库(ws)。 当我们运行这样一个简单的例子时:

var express = require('express');
var http = require('http');
var WebSocket = require('ws');

const app = express();

//initialize a simple http server
const server = http.createServer(app);

//initialize the WebSocket server instance
const wss = new WebSocket.Server( server );

wss.on('connection', function connection(ws) {

    //connection is up, let's add a simple simple event
    ws.on('message', function incoming(message) {

        //log the received message and send it back to the client
        console.log('received: %s', message);
        ws.send('Hello, you sent -> '+ message);
    });

    //send immediatly a feedback to the incoming connection    
    ws.send('Hi there, I am a WebSocket server');
});

//start our server
server.listen(process.env.PORT || 8999, () => {
    console.log('Server started on port'+ server.address().port + ' 
:)');
});

但是当我们运行应用程序时,我们遇到了这个错误:

ws constants.js:8 EMPTY_BUFFER: Buffer.alloc(0), ^ TypeError: 
Buffer.alloc is not a function

你知道它是什么吗?由于版本冲突,谷歌在几个案例中指出。 如果我输入:nodejs -v它让我走了:v 4.2.6

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我已经发现了问题......这是一个包版本问题。

我卸载所有内容,然后使用以下行重新安装有关nodejs的所有内容:

curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs

我升级到nodejs 8.x.之后,重新开始我的会话,一切正常。 后来我发现了一些关于使用WS库的正确版本的评论。

问候!