(一) 第一个 node 应用
- 新建 app.js,代码如下
var http = require('http');http.createServer(function (request, response) {// 发送 HTTP 头部// HTTP 状态值: 200 : OK// 内容类型: text/plainresponse.writeHead(200, {'Content-Type': 'text/plain'});response.end('Hello World');}).listen(8888);// 终端打印如下信息console.log('Server running at http://127.0.0.1:8888/');
- 启动服务
node app.js
(二) nodejs 的模块系统
1. nodejs模块系统介绍
一个js文件就是一个模块, 一个模块会有一些变量或者方法,可以导出这些变量或者方法提供给别的模块进行使用, 它也可以导入别的模块或者方法来使用
2. 导出模块和导入模块
// 例子1
// m1.js, 导出一个数组, 导出使用module.exportsmodule.exports = [1,2,3];// index1.js 导入m1模块, 导入用 require(模块路径)let list = require('./m1');console.log(list);// 运行index1.jsnode index1.js
// 例子2
// m2.js 导出一个函数function add(a,b) {return a+b;}module.exports = add;// index2.js 导入m2模块let add = require('./m2');// 调用m2中的add方法let sum = add(100, 200);console.log('sum', sum);// 运行 index2.jsnode index2.js
// 例子3
// m3.js 导出一个对象var username = '张三';var age = 100;function say() {console.log('我是' + username);}module.exports = {username: username,age: age,say: say}// index3.js 导入m3模块let obj = require('./m3');console.log('用户名', obj.username);obj.say();// 运行 index3.jsnode index3.js
(三) 文件系统
- 读取文件 ```javascript // 例子1 异步读取文件内容, 需要新建nput.txt文件, 内容随意 // index1.js var fs = require(“fs”);
console.log(1); // 异步读取 fs.readFile(‘input.txt’, function(err, data) { console.log(2); if (err) { return console.error(err); } else { console.log(“异步读取: “ + data.toString()); }
}); console.log(3);
```javascript// 例子2 新建index2.js, 同步读取文件内容var fs = require('fs');// 同步读取var data = fs.readFileSync('input.txt');console.log("同步读取: " + data.toString());console.log("程序执行完毕。");
- 写入文件 ```javascript // 例子1 异步写入文件内容 var fs = require(“fs”);
console.log(“准备写入文件”); var str = ‘困难是我们的食物’;
fs.writeFile(‘data.txt’, str, function (err) { if (err) { return console.error(err); } console.log(‘文件写入成功’) });
```javascript// 例子2 同步读取var fs = require("fs");var str = '困难是我们的食物';fs.writeFileSync('data.txt', str);console.log('文件写入成功');// 添加trycatch可以捕捉写入过程中发生的错误try {fs.writeFileSync('data.txt', str);console.log('文件写入成功');} catch (error) {console.log('错误信息', error);}
(四) nodejs原生路由
路由介绍: 路由字面意思是”途经”, 路途经过什么地方的意思,没有两个地方的风景是一样, 所以你经过不同的地方, 看到的风景是不一样的,网站上的路由也类似这样的意思, 你访问不同的url, 那么你看到的东西也是不一样的。
// app.js nodejs原生路由简单例子var http = require("http");var fs = require("fs");http.createServer((req, res) => {switch (req.url) {case "/hello":res.write("hello");res.end();break;case "/hehe":res.write("hehe");res.end();break;case "/my":// 新建data.json文件,里面写一些json数据fs.readFile("data.json", (error, data) => {if (error) throw error;res.write(data);res.end();});break;default:res.write("this is home");res.end();break;}}).listen(3000, "localhost", () => {console.log("服务器运行在:http://localhost:3000");});
// 运行代码node app.js// 访问以下地址看看有什么不一样http://localhost:3000/hellohttp://localhost:3000/hehehttp://localhost:3000/myhttp://localhost:3000
(五) path模块
path模块介绍: nodejs自带的模块, 主要用来解决路径相关问题
- path.join(),因为window和linux系统分割符不一致,join可以解决这个问题
let path = require('path')let str1 = path.join('/nodejs','dist');console.log(str1); // /nodejs/distlet str2 = path.join('\\nodejs','dist');console.log(str2); // /nodejs/dist
- path.resolve 把路径变成绝对路径
let path = require('path')let str = path.resolvepath.resolve('nodejs','dist');console.log(str); // C:\Users\Administrator\Desktop\web04\nodejs\path\nodejs\dist
- __dirname 当前目录
let path = require('path');console.log(__dirname);let str = path.resolve(__dirname,'dist');console.log('str',str);
(六) npm 工具
- npm 是什么
- 前端通用的模块都存放在网站 https://www.npmjs.com/, 你需要用到nodejs模块在这个网站都能找到
- npm 是 nodejs 模块 (一般称为包,一个模块就是一个包) 管理工具
初始化 package.json
npm init // 或npm init -y
安装一个 nodejs 模块
// 以jquery和axios为例,安装用npm install(简写i)npm i jquery --save /// 记录在 dependenciesnpm i axios --save-dev // 记录devDependenciesnpm i serve -g // 全局安装,serve是一个封装了nodejs服务的模块npm i // 当我们把node_modules删掉,使用npm i 可以把所有依赖都安装回来
// dependency和devDependencies的区别
(1) 使用 --save-dev 安装的 插件,被写入到 devDependencies 域里面去,而使用 --save 安装的插件,则是被写入到 dependencies 区块里面去。(2) 官方解释“dependency”:These packages are required by your application in production.(这些软件包是生产中的应用程序需要的)“devDependencies”: These packages are only needed for development and testing.(这些包仅用于开发和测试)(3) package.json 文件里面的 devDependencies 和 dependencies 的区别devDependencies 里面的插件只用于开发环境,不用于生产环境,而dependencies是需要发布到生产环境的。比如我们写一个项目要依赖于jQuery,没有这个包的依赖运行就会报错,这时候就把这个依赖写入dependencies;而我们使用的一些构建工具比如glup、webpack这些只是在开发中使用的包,上线以后就和他们没关系了,所以将它写入devDependencies。
更新 nodejs 模块
npm update xxx
删除 nodejs 模块
npm uninstall xxx
运行指令 (运行package.json里script里的指令)
npm run xxx
(七) 设置淘宝镜像
(1) 输入以下命令
npm config set registry https://registry.npm.taobao.org
(2) 验证
npm config get registry
(3) 如果返回https://registry.npm.taobao.org,说明镜像配置成功。
(4) nrm模块也可以帮助我们进行镜像的切换
npm i nrm -g // 全局安装nrm模块nrm ls // ls查看可用镜像nrm use xxx // 使用镜像
(八) nodejs版本切换
- 下载安装 nvm
https://nvm.en.softonic.com/
- nvm命令
nvm // 会提示nvw下的相关命令nvm ls // 查看已安装node版本nvm install 10 // 安装对应10.0版本的nodenvm uninstall 10 // 卸载对应10.0版本的nodenvm use xxx // 选择使用XXX版本
(九) 服务器自动重启
全局安装
nodemonnpm i nodemon -g
运行
node app.js需要使用nodemon app.js来代替- 示例: 新建
app.js, 然后执行nodemon app.js, 然后修改输出内容试试
var http = require('http');http.createServer(function (request, response) {// 发送 HTTP 头部// HTTP 状态值: 200 : OK// 内容类型: text/plainresponse.writeHead(200, {'Content-Type': 'text/plain'});response.end('Hello World');}).listen(8888);// 终端打印如下信息console.log('Server running at http://127.0.0.1:8888/');
(十) 调试代码
参考链接: https://www.ruanyifeng.com/blog/2018/03/node-debugger.html
最简单的一种方法:
执行
nodemon app.js时添加--inspectnodemon --inspect app.js
执行以上命令之后, 打开控制台, 左上角有个绿色的按钮, 点击它会弹出一个控制台
- 快捷键
ctrl+p, 然后输入app.js, 接下来的事情就跟调试前端代码一样了
