如何安装 Node.js、npm、socket.io 并使用它们? [英] How to install Node.js, npm, socket.io and use them?

查看:63
本文介绍了如何安装 Node.js、npm、socket.io 并使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Node.js 的新手
有人可以解释我如何逐步安装 Node.js、npm 和 socket.io.

I am newbie to Node.js
Can someone explain me how can I install Node.js, npm and socket.io step by step.

谢谢.

推荐答案

1.. 前往 http://nodejs.org 并点击安装按钮

1.. Go to http://nodejs.org and click on Install button

2.. 下载节点并安装

2.. Download node and install it

3.. 在硬盘上创建一个空文件夹

3.. Create an empty folder on your hard disk

4.. 创建一个 package.json 文件,内容如下

4.. Create an package.json file with the following content

{
    "name": "App",
    "version": "0.0.1",
    "description": "App",
    "dependencies": {
        "socket.io": "latest"
    },
    "author": "developer"
}

5.. 打开 windows 的命令提示符(按 Windows 键 + R 并输入 cmd)

5.. Open windows's command prompt (press Windows key + R and type cmd)

6.. 使用 cd 命令导航到您新创建的目录

6.. Navigate to your newly created directory with cd command

7.. 在该目录中输入 npm install

7.. Type npm install in that directory

8.. 等到所有东西都下载并安装好

8.. Wait till everything is downloaded and installed

9.. 创建一个 app.js 文件,内容如下:

9.. Create a file app.js with the following content:

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(3000);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

10.. 使用以下内容创建文件 index.html

10.. Create a file index.html with the following content

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

11.. 再次进入命令提示符(控制台)并输入 node app.js.这将运行 nodejs 服务器,您可以打开 localhost:3000

11.. Again, go to the command prompt (console) and type node app.js. This will run nodejs server and you may open localhost:3000

这篇关于如何安装 Node.js、npm、socket.io 并使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆