小木木 发表于 2017-2-21 08:42:41

Learn Nodejs 01

  (1)下载nodejs

https://nodejs.org/download/

选择相应的版本进行下载

 

 

(2)安装nodejs

安装的方式比较多,请baidu下
  我这边下载的是“node-v0.12.7-linux-x64.tar.gz”这个版本

(1)上传服务器

(2)解压

tar -zxvf node-v0.12.7-linux-x64.tar.gz
(3)检测是否安装成功

/database/nodejs/node-v0.12.7-linux-x64/bin

 

 


  # ./node -v
v0.12.7

 

(3)编写HelloWorld

(3.1)新建工作区域 workspace



(3.2)新建第一个项目helloworld
  /database/nodejs/workspace/helloworld

(3.3)编写js

vim first.js

拷贝官方网站上的代码

var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(1337, '202.102.83.169');
console.log('Server running at http://202.102.83.169:1337/');

  # cat first.js 

 
  var http = require('http');

 
  http.createServer(function (req, res) {

 
  res.writeHead(200, {'Content-Type': 'text/plain'});

 
  res.end('Hello World\n');

 
  }).listen(1337, '202.102.83.169');

 
  console.log('Server running at http://202.102.83.169:1337/');

 

注意点:这个时候访问“http://202.102.83.169:1337/”无效

 

 

server.listen(port, , , )#
Begin accepting connections on the specified port and hostname. If the hostname is omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY).



    里面说到如果忽略了hostname,那么服务器将会接受所有IPV4地址的链接,IPv4地址包括127.0.0.1 localhost和本地IP。没有认真看API,以后要注意。那么这样做就可以实现监听本地IP、localhost、127.0.0.1了:

?



1

2

3

4

5



var http = require('http');

http.createServer(function (req, res) {

  res.writeHead(200, {'Content-Type': 'text/plain'});

  res.end('Hello World\n');

}).listen(1337);











 

 

 

(3.4)启动服务
  # ./node /database/nodejs/workspace/helloworld/first.js 

 
  Server running at http://127.0.0.1:1337/

 

(3.5)启动服务

浏览器访问

 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 
页: [1]
查看完整版本: Learn Nodejs 01