Node.js 的安装与配置

本章节我们将向大家介绍在各个平台上(win,mac与ubuntu)安装Node.js的方法。本安装教程以 Latest LTS Version: 8.11.1 (includes npm 5.6.0) 版本为例

注:Node.js 10 将在今年十月份成为长期支持版本, 使用npm install -g npm升级为npm@6,npm@6性能提升了17倍

安装Node.js

Node.js 有很多种安装方式,进入到Node.js的官网,我们点击 Download 即可下载各个平台上的Node.js。在Mac / Windows 平台我们可以直接下载安装包安装,就像安装其他软件一样。在Ubuntu 可以通过 apt-get 来安装*(CentOS 使用 yum )* , Linux 用户推荐使用源码编译安装。

在 Node.js 的官网 你会发现两个版本的Node.js,LTS 是长期支持版,Current 是最新版

安装完成后在命令行输入

node -v
# v8.11.1
1
2

使用 nvm

nvm是Node版本管理器。nvm不支持Windows 可使用nvm-windows 代替

我们可以使用curl或者wget安装。

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
1
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
1

注:安装完重启下命令行

使用nvm可以方便的下载安装删除各个版本的Node.js

nvm install node # 安装最新稳定版 node,现在是 v10.0.0
nvm install lts/carbon #安装 v8.11.1

# 使用nvm use切换版本
nvm use v6.14.2 #切换至 v6.14.2 版本

nvm ls # 查看安装的node版本。
1
2
3
4
5
6
7

具体使用请参考nvm官网

一些有用的工具

cnpm 淘宝 NPM 镜像

nrm 快速切换 NPM 源

由于我国的网络环境,npm源访问会很慢,这时我们可以使用cnpm 或是 用nrm把源换成能国内的

cnpm 安装

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

或是使用nrm

# 下载包
npm install -g nrm

# 使用
nrm ls
* npm -----  https://registry.npmjs.org/
  cnpm ----  http://r.cnpmjs.org/
  taobao --  https://registry.npm.taobao.org/
  nj ------  https://registry.nodejitsu.com/
  rednpm -- http://registry.mirror.cqupt.edu.cn
  skimdb -- https://skimdb.npmjs.com/registry
  
# 使用淘宝的源
nrm use taobao
1
2
3
4
5
6
7
8
9
10
11
12
13
14

hello node

到此想必各位已经在本机上搭建好了node环境,来个 hello world 结束本文

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14

启动服务

$ node app.js
Server running at http://127.0.0.1:3000/
1
2

每次改的代码都要重启很麻烦,使用supervisor实现监测文件修改并自动重启应用。

Node.js入门教程