[关闭]
@breakerthb 2016-07-11T06:31:02.000000Z 字数 2196 阅读 1292

NodeJS-Basic

NodeJS


NodeJS基础

标签(空格分隔): Server NodeJS


NodeJS教程

Installation

$ sudo apt-get install g++ curl libssl-dev apache2-utils python build-essential gcc
	$ sudo add-apt-repository ppa:chris-lea/node.js
$ sudo apt-get update
	$ sudo apt-get install nodejs
$ sudo apt-get install node
	$ sudo apt-get install npm

1. NodeJS安装

直接执行node程序,根据系统提示安装

$ node

如果没有安装node,apt-get会提示如何安装

2. npm安装

$ sudo apt-get install npm
	$ npm -v

如果不是最新版本,使用这条命令更新

$ sudo npm install npm -g

说明:后面加-g是全局安装,不加则是本地安装。

NPM使用介绍

3. 其他平台安装

请参考: http://www.runoob.com/nodejs/nodejs-install-setup.html

Demo

// Demo.js
import SimpleHTTPServer

SimpleHTTPServer.test()

保存文件后执行命令:

$ node Demo.js

在Client端输入网址,可以看到下面的结果:

forever

使NodeJS服务在后台一直执行。

最简单的办法:

$ nohup node app.js &

但是,forever能做更多的事情,比如分别记录输出和错误日志,比如可以在js中作为api使用。

$ sudo npm install forever -g   #安装
	$ forever start app.js          #启动
$ forever stop app.js           #关闭
	$ forever start -l forever.log -o out.log -e err.log app.js   #输出日志和错误

命令语法及使用 https://github.com/nodejitsu/forever

Express

$ npm install express

$ npm install express -g

1. 本地安装

2. 全局安装

3. 查看全局安装模块

$ npm ls -g

4. 属性文件

node_modules/express/package.json

5. 卸载模块

$ npm uninstall express

6. 更新模块

$ npm update express

7. 搜索模块

$ npm search express

NodeJS应用的组成

NodeJS提供服务主要靠以下三个部分:

用 require 指令来载入 Node.js 模块。

服务器可以监听客户端的请求,类似于 Apache 、Nginx 等 HTTP 服务器。

服务器很容易创建,客户端可以使用浏览器或终端发送 HTTP 请求,服务器接收请求后返回响应数据。

创建NodeJS应用

步骤一:引入 required 模块

使用 require 指令来载入 http 模块,并将实例化的 HTTP 赋值给变量 http,实例如下:

var http = require("http");

步骤二:创建服务器

使用 http.createServer() 方法创建服务器,并使用 listen 方法绑定 8888 端口。函数通过 request, response 参数来接收和响应数据。代码如下:

// server.js
var http = require('http');

http.createServer(function (request, response) {

    // 发送 HTTP 头部 
    // HTTP 状态值: 200 : OK
    // 内容类型: text/plain
    response.writeHead(200, {'Content-Type': 'text/plain'});

    // 发送响应数据 "Hello World"
    response.end('Hello World\n');
}).listen(8888);

// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

以上代码我们完成了一个可以工作的 HTTP 服务器。

使用 node 命令执行以上的代码:

$ node server.js
Server running at http://127.0.0.1:8888/

cmdrun

接下来,打开浏览器访问 http://127.0.0.1:8888/,你会看到一个写着 "Hello World"的网页。

nodejs-helloworld

分析:

第一行请求(require)Node.js 自带的 http 模块,并且把它赋值给 http 变量。
接下来我们调用 http 模块提供的函数: createServer 。这个函数会返回 一个对象,这个对象有一个叫做 listen 的方法,这个方法有一个数值参数, 指定这个 HTTP 服务器监听的端口号。

实例演示

http://www.runoob.com/wp-content/uploads/2014/03/node-hello.gif

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注