1 基础

为什么

JavaScript是运行在浏览器的脚本。为了能让JavaScript在服务器上运行,执行服务器上的业务逻辑,产生了NodeJS。

是什么

Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台。
Node.js是一个事件驱动I/O服务端JavaScript环境。

优势

  • 单线程高并发。通过JS的回调方法,实现了并发。
  • 自带web服务器模块。

2 helloworld

server.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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/');
1
node server.js

3 NPM

nodeJS的包管理器。

安装

1
2
3
4
5
6
$ npm install <Module Name>
$ npm uninstall express

npm install express # 本地安装
npm install express -g # 全局安装
npm install express@1.3.4 # 指定版本安装

查看

1
2
3
4
npm list -g
npm ls
npm search express
npm info jquery 查看jQuery相关的信息

创建

1
2
3
npm init//创建npm模块
npm adduser//注册npm
npm publish//发布模块

初始化依赖

1
npm install

package.json

  • name - 包名。
  • version - 包的版本号。
  • description - 包的描述。
  • homepage - 包的官网 url 。
  • author - 包的作者姓名。
  • contributors - 包的其他贡献者姓名。
  • dependencies - 依赖包列表。如果依赖包没有安装,npm 会自动将依赖包安装在 node_module 目录下。
  • repository - 包代码存放的地方的类型,可以是 git 或 svn,git 可在 Github 上。
  • main - main 字段指定了程序的主入口文件,require(‘moduleName’) 就会加载这个文件。这个字段的默认值是模块根目录下面的 index.js。
  • keywords - 关键字