一、linux下安装nodejs
-
下载安装包(node-v10.15.0-linux-x64.tar.xz)
-
使用winSCP上传到/software目录下
-
解压到当前目录
[root@localhost software]# tar -Jxvf node-v10.15.0-linux-x64.tar.xz
[root@localhost software]# ls
apache-tomcat-9.0.14 jdk1.8.0_201 node-v10.15.0-linux-x64.tar.xz zTree_v3-3.5.33.zip
apache-tomcat-9.0.14.tar.gz jdk-8u201-linux-x64.tar.gz screen-4.6.2
gcc-8.2.0.tar.gz node-v10.15.0-linux-x64 screen-4.6.2.tar.gz -
创建软链接(和下面的二选一)
[root@localhost software]# ln -s /software/node-v10.15.0-linux-x64/bin/node /usr/local/bin/node
[root@localhost software]# ln -s /software/node-v10.15.0-linux-x64/bin/npm /usr/local/bin/npm
[root@localhost software]# ln -s /software/node-v10.15.0-linux-x64/bin/npx /usr/local/bin/npx
-
配置环境变量(和上面的二选一)
在node-v10.15.3版本中node的bin目录下没有npm和npx文件,而是npm和npx的连接,这样再次创建软连接的时候会失败,所以这里直接在环境变量里面配置
在/etc/profile
文件末尾添加以下两行:
export NODE_HOME=/soft/node-v10.15.3-linux-x64
export PATH=$NODE_HOME/bin:$PATH -
测试安装情况
[root@localhost software]# node -v
v10.15.0
解释: 到这里nodejs就已经安装成功了
二、写一个express应用
- 新建文件夹(testnode)
[root@localhost software]# mkdir /root/testnode
- 初始化package.json
[root@localhost software]# cd /root/testnode
[root@localhost testnode]# npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install ` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (testnode)
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to /root/testnode/package.json:
{
“name”: “testnode”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo “Error: no test specified” && exit 1”
},
“author”: “”,
“license”: “ISC”
}
Is this OK? (yes) - 安装express
[root@localhost testnode]# npm i express --save
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN testnode@1.0.0 No description
npm WARN testnode@1.0.0 No repository field.
+ express@4.16.4
added 48 packages from 36 contributors in 2.529s - 编写index.js
[root@localhost testnode]# vi index.js
const express = require(‘express’);
const app=express();
app.use(express.static(‘public’));
app.listen(3000,()=>{
console.log(‘express listen on 3000…success!’);
}); - 新建public目录和public/index.html
[root@localhost testnode]# mkdir ./public
[root@localhost testnode]# touch ./public/index.html
- 编辑index.html
[root@localhost testnode]# vi ./public/index.html
<html>
<head>
<title>这是linux测试nodejs的页面</title>
</head>
<body>
hello,linux测试nodejs环境!
</body>
</html> - 启动这个服务
[root@localhost testnode]# node index.js
express listen on 3000…success! - 浏览器访问 http://192.168.114.134:3000/