Node.js 简单知识

下载及安装

windows

  • 直接在Nodejs官网下载安装 (简单)
  • 版本推荐6.10+,暂可不用下载最新版本v7

测试是否安装成功

CMD 下输入

1
2
node -v
npm -v

可以正常显示相应的版本即为安装成功

若失败,检查系统环境变量PATH是否已配置了Nodejs

未添加可手动添加

Linux

ubuntu

1
2
sudo apt-get install nodejs
//这种方法安装的版本一般比较低,很多包会用不了

官方教程

1
2
3
4
5
6
7
8
9
10

//若安装 5.x 版本是:
curl -sL https://deb.nodesource.com/setup_5.x | bash -
apt-get install nodejs -y

//想要安装 6.x 版本就是
curl -sL https://deb.nodesource.com/setup_6.x | bash -
apt-get install nodejs -y

//如此一来,安装出来的版本就是最新的,npm 也是最新

centOS

1
sudo yum install nodejs

源码安装

  • 较麻烦, 但是好处多. 不介绍, 以后自学.

编译器

webStorm / VScode

webStorm 可学生认证,免费使用

创建第一个应用

引入模块

使用 require 关键字

1
var http = require("http");

创建服务器

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
2
node server.js
Server running at http://127.0.0.1:8888/

NPM

NPM Node Package Manager

NPM 是随同 NodeJS 一起安装的包管理工具,能解决 NodeJS 代码部署上的很多问题,常见的使用场景有以下几种:

  1. 允许用户从 NPM 服务器下载别人编写的第三方包到本地使用。
  2. 允许用户从 NPM 服务器下载并安装别人编写的命令行程序到本地使用。
  3. 允许用户将自己编写的包或命令行程序上传到 NPM 服务器供别人使用。

NPM 常用命令

  • npm install [-g]
  • npm help
  • npm update [-g]

改用淘宝npm镜像

国内直接使用 npm 官方镜像速度非常慢,推荐使用淘宝 NPM 镜像。
淘宝 NPM 镜像是一个完整 npm 镜像,可以用此代替官方版本,同步频率目前为 10 分钟 一次以保证尽量与官方服务同步。

替换方式

1
npm install -g cnpm --registry=https://registry.npm.taobao.org

使用方法

同 npm 一样, 除了publish命令, 其他命令都可直接使用.
例如

1
cnpm install [package]

如何找包

package.json

记录项目相关的基本信息、组件依赖信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
{
"name": "SFMS",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"repository": {
"type": "git",
"url": "git@127.0.0.1:bitzo/SFMS.git"
},
"keywords": [
"SFMS",
"Manage System"
],
"author": "bitzo",
"license": "MIT",
"homepage": "http://127.0.0.1:1320/bitzo/SFMS",
"dependencies": {
"async": "*",
"body-parser": "~1.15.2",
"cookie-parser": "~1.4.3",
"excel-export": "^0.5.1",
"express": "~4.14.0",
"express-session": "~1.14.2",
"formidable": "^1.1.1",
"jade": "~1.11.0",
"jwt-simple": "^0.2.0",
"log4js": "1.0.1",
"mocha": "*",
"moment": "*",
"mysql": "*",
"node-schedule": "^1.2.0",
"redis": "^2.6.3",
"sha1": "*",
"should": "*",
"superagent": "*",
"supertest": "*",
"validator": "*",
"xml2js": "*"
}
}

尝试写一个简单的服务

……

nodeJS 常用官方模块

BufferConsoleCryptoEventFile System

HTTPModulestreamPathQuery StringURL

查看相关的 官方文档 学习

学习 Express 框架

Express 官网: 学习入门/大致了解API

其它

学习资源