我有一個nodejs語言的文件,我在互聯網上找到了,我想運行它,但我不知道如何運行它。我嘗試用cmd命令運行:node server.js,但它不起作用。如何使用Node.js運行用js編寫的server.js
server.js
文件
var port = process.env.PORT || 3000;
server = require('http').createServer(),
io = require('socket.io').listen(server),
users = {}, socks = {};
function Uid() { this.id = ++Uid.lastid; }
Uid.lastid = 0;
//Handle users
io.sockets.on('connection', function (socket) {
\t // Event received by new user
\t socket.on('join', function (recv) {
\t \t if (!recv.user) {
\t \t \t socket.emit('custom_error', { message: 'User not found or invalid' });
\t \t \t return;
\t \t }
\t \t // The user already exists
\t \t if (users[recv.user]) {
\t \t \t socket.emit('custom_error', { message: 'The user '+ recv.user +' already exists' });
\t \t \t return;
\t \t }
\t \t // If there is users online, send the list of them
\t \t if (Object.keys(users).length > 0)
\t \t \t socket.emit('chat', JSON.stringify({ 'action': 'usrlist', 'user': users }));
\t \t // Set new uid
\t \t uid = new Uid();
\t \t socket.user = recv.user;
\t \t // Add the new data user
\t \t users[socket.user] = {'uid': Uid.lastid, 'user': socket.user, 'name': recv.name, 'status': 'online'}
\t \t socks[socket.user] = {'socket': socket}
\t \t // Send new user is connected to everyone
\t \t socket.broadcast.emit('chat', JSON.stringify({'action': 'newuser', 'user': users[socket.user]}));
\t });
\t // Event received when user want change his status
\t socket.on('user_status', function (recv) {
\t \t users[socket.user].status = recv.status;
\t \t socket.broadcast.emit('chat', JSON.stringify({'action': 'user_status', 'user': users[socket.user]}));
\t });
\t // Event received when user is typing
\t socket.on('user_typing', function (recv) {
\t \t var id = socks[recv.user].socket.id;
\t \t io.sockets.socket(id).emit('chat', JSON.stringify({'action': 'user_typing', 'data': users[socket.user]}));
\t });
\t // Event received when user send message to another
\t socket.on('message', function (recv) {
\t \t var id = socks[recv.user].socket.id;
\t \t var msg = {'msg': recv.msg, 'user': users[socket.user]};
\t \t io.sockets.socket(id).emit('chat', JSON.stringify({'action': 'message', 'data': msg}));
\t });
\t // Event received when user has disconnected
\t socket.on('disconnect', function() {
\t \t socket.broadcast.emit('chat', JSON.stringify({'action': 'disconnect', 'user': users[socket.user]}));
\t \t //socket.broadcast.emit('chat', JSON.stringify({'action': 'offline', 'user': users[socket.user]}));
\t \t delete users[socket.user];
\t \t delete socks[socket.user];
\t });
});
//Listen to the server port
server.listen(port, function() {
var addr = server.address();
console.log('jquery-chat server listening and ready');
});
你有什麼錯誤嗎?這意味着什麼「但它不工作」? –
是的,我得到一個錯誤:不能找到模塊「socket.io」在... –
然後,你沒有安裝socket.io模塊。看看這個鏈接來安裝socket.io http://socket.io/download/ –