Skip to content

06 Node.js 入门 ​

知识点自测 ​

  1. 从 index.js 出发,访问到 student/data.json 的相对路径如何写?

    bash
    My-Project
    ├── public
    │   ├── student
    │   │   └── data.json
    │   └── teacher
    │       └── data.json
    └── utils
        └── index.js
    • A. ../public/teacher/data.json
    • B. ./public/student/data.json
    • C. ../student/data.json
    答案
    • A 选项正确
  2. 如下代码运行结果是多少?

    js
    const str = `我们都是好人,好人就是我`;
    const result = str.replace(/好/g, '');
    • A. 我们都是人,好人就是我
    • B. 我们都是人,人就是我
    答案
    • B 选项正确
  3. 以下哪个正则表达式,能匹配字符串中的小括号?

    • A. /(/
    • B. /\(/
    答案
    • B 选项正确,因为在正则表达式里直接写小括号,相当于分组功能,而不是匹配字符串小括号里,可以加一个斜杠代表转义,转换它去匹配小括号字符串而不再是分组
  4. 如下代码返回的结果是什么?

    js
    const str = '/api/hello?a=10&b=20';
    const result = str.startsWith('/api/hello');
    • A. true
    • B. false
    答案
    • A 项正确,startsWith 用于判断调用的字符串是否以传入的目标字符串开头,是返回 true,否则返回 false 在原地

什么是 Node.js ​

什么是 Node.js,有什么用,为何能独立执行 JS 代码,演示安装和执行 JS 文件内代码

  1. Node.js 是一个独立的 JavaScript 运行环境,能独立执行 JS 代码,因为这个特点,它可以用来编写服务器后端的应用程序

  2. Node.js 作用除了编写后端应用程序,也可以对前端代码进行压缩,转译,整合等等,提高前端开发和运行效率

  3. Node.js 基于 Chrome V8 引擎封装,独立执行 JS 代码,但是语法和浏览器环境的 V8 有所不同,没有 document 和 window 但是都支持 ECMAScript 标准的代码语法

  4. 想要得到 Node.js 需要把这个软件安装到电脑,在素材里有安装程序(window 和 mac 环境的)参考 PPT 默认下一步安装即可

    powershell
    scoop search nodejs # 搜索 Node.js
    scoop install nodejs16 # 安装 nodejs16(课程里的 Node.js 版本)
    scoop install nodejs # 安装 Node.js 最新版
    scoop install nodejs-lts # 安装 Node.js LTS 版本
    powershell
    scoop install fnm # 安装 fnm
    fnm env --node-dist-mirror https://mirrors.tuna.tsinghua.edu.cn/nodejs-release/ # 设置 TUNA 镜像
    fnm list-remote # 查看可安装的 Node.js 版本
    fnm install v16.20.2 # 安装 Node.js 16(课程里的 Node.js 版本)
    fnm install --latest # 安装 Node.js 最新版
    fnm install --lts # 安装 Node.js LTS 版本
  5. Node.js 没有图形化界面,需要使用 cmd 终端命令行(利用一些命令来操控电脑执行某些程序软件)输入,node -v 检查是否安装成功

    powershell
    > node -v
    v18.18.2
    
    > fnm list
    * v18.18.2 default, lts-latest
    * system
  6. 新建 index.js 文件,编写打印 helloworld 和 for 循环打印 3 个 6

    js
    /**
     * 目标:编写 js 代码,用 node 命令执行
     * 终端作用:敲击命令,调用对应程序执行
     * 终端打开:目标文件->右键->在集成终端中打开
     * 命令:node xxx.js(注意路径)
     */
    console.log('hello world');
    
    for (let index = 0; index < 3; index++) {
      console.log(6);
    }
    
    // ❯ node .\01.helloworld.js
    // hello world
    // 6
    // 6
    // 6
  7. Node.js 执行目标 JS 文件,需要使用 node xxx.js 命令来执行

    • 我们可以借助 VSCode 集成终端使用

    • 好处:可以快速切换到目标 JS 文件所在终端目录,利用相对路径找到要执行的目标 JS 文件

      • 使用 Ctrl + ~ 打开终端
      • 使用 Ctrl + Shift + ~ 新建终端
      • 终端中输入 node xxx.js 执行目标 JS 文件

小结 ​

  1. Node.js 有什么用?

    • 编写后端程序,提供数据和网页资源,还可以作为前端工程化的工具,翻译压缩整合代码等,提高开发效率
  2. Node.js 为何能执行 JS 代码?

    • 基于 Chrome 的 V8 引擎封装
  3. Node.js 与浏览器环境的 JS 最大区别?

    • Node.js 环境中没有 BOM 和 DOM,但是也用 JS 语法
  4. Node.js 如何执行代码?

    • 在 VSCode 终端中输入:node xxx.js 回车即可执行(注意路径)

fs 模块 - 读写文件 ​

了解模块概念,使用 fs 模块封装的方法读写文件内容

  1. 模块:类似插件,封装了方法和属性供我们使用

  2. fs 模块:封装了与本机文件系统进行交互的 方法和属性

  3. fs 模块使用语法如下:

    js
    // 加载 fs 模块,得到 fs 对象
    const fs = require('fs');
    
    // 写入文件内容
    fs.writeFile('文件路径', '写入内容', (err) => {
      // 写入后的回调函数
    });
    
    // 读取文件内容
    fs.readFile('文件路径', (err, data) => {
      // 读取后的回调函数
      // data 是文件内容的 Buffer 数据流
    });
案例 - 向 test.txt 文件写入内容并读取打印
js
/**
 * 目标:使用 fs 模块,读写文件内容
 * 语法:
 * 1. 引入 fs 模块
 * 2. 调用 writeFile 写入内容 (注意:建议写入字符串内容,会覆盖目标文件所有内容)
 * 3. 调用 readFile  读取内容
 */
const fs = require('fs');

fs.writeFile('./02.test.txt', '欢迎使用 fs 模块读写文件内容', (err) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log('写入成功');
});

fs.readFile('./02.test.txt', (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`data: ${data}`); // data 是文件内容的 Buffer 数据流
  console.log(`data.toString(): ${data.toString()}`); // 读取的内容是二进制数据,需要转换成字符串
});

// ❯ node .\02.fs.js
// 写入成功
// data: 欢迎使用 fs 模块读写文件内容
// data.toString(): 欢迎使用 fs 模块读写文件内容

小结 ​

  1. 什么是模块?

    • 类似插件,封装了方法和属性
  2. fs 模块的作用?

    • 读写本机文件内容

path 模块 - 路径处理 ​

使用 path 模块来得到绝对路径

  1. 为什么在 Node.js 待执行的 JS 代码中要用绝对路径:

    Node.js 执行 JS 代码时,代码中的路径都是以终端所在文件夹出发查找相对路径,而不是以我们认为的从代码本身出发,会遇到问题,所以在 Node.js 要执行的代码中,访问其他文件,建议使用绝对路径

  2. 新建 03 文件夹编写待执行的 JS 代码,访问外层相对路径下的文件,然后在最外层终端路径来执行目标文件,造成问题

  3. 问题原因:就是从代码文件夹出发,使用 ../test.txt 解析路径,找不到目标文件,报错了!

  4. 解决方案:使用模块内置变量 __dirname 配合 path.join() 来得到绝对路径使用

  5. 再次执行查看问题就被修复了!以后在 Node.js 要执行的 JS 代码中访问其他文件的路径,都建议使用绝度路径

js
/**
 * 目标:在 Node.js 环境的代码中,应使用绝对路径
 * 原因:代码的相对路径是以终端所在文件夹为起点,而不是 Vscode 资源管理器
 *  容易造成目标文件找不到的错误
 */
const fs = require('fs');

fs.readFile('../02.test.txt', (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`data: ${data}`);
});

// ❯ node .\03.path\index.old.js
// [Error: ENOENT: no such file or directory, open 'E:\git\code\ajax\黑马 AJAX\02.test.txt'] {
//   errno: -4058,
//   code: 'ENOENT',
//   syscall: 'open',
//   path: 'E:\\git\\code\\ajax\\黑马 AJAX\\02.test.txt'
// }
js
/**
 * 目标:在 Node.js 环境的代码中,应使用绝对路径
 * 原因:代码的相对路径是以终端所在文件夹为起点,而不是 Vscode 资源管理器
 *  容易造成目标文件找不到的错误
 */
const fs = require('fs');
const path = require('path');
console.log(__dirname);

fs.readFile(path.join(__dirname, '../02.test.txt'), (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  console.log(`data: ${data}`);
});

// ❯ node .\03.path\index.js
// E:\git\code\ajax\黑马 AJAX\47.nodejs\03.path
// data: 欢迎使用 fs 模块读写文件内容

小结 ​

  1. path.join() 方法有什么用?

    • 按照所在本机系统的分隔符作为定界符来链接你传入的路径
  2. __dirname 模块内置变量的值是多少?

    • 动态获取当前文件所在文件夹的绝对路径

案例 - 压缩前端 html ​

压缩前端代码,体验前端工程化的例子

  1. 前端工程化:前端代码压缩,整合,转译,测试,自动部署等等工具的集成统称,为了提高前端开发项目的效率

  2. 需求:把准备好的 html 文件里的回车符 \r 和换行符 \n 去掉进行压缩,写入到新 html 中

  3. 步骤:

    • 读取源 html 文件内容
    • 正则替换字符串
    • 写入到新的 html 文件中,并运行查看是否能正常打开网页
案例 - 压缩前端 html
js
/**
 * 目标 1:压缩 html 代码
 * 需求:把回车符 \r,换行符 \n 去掉,写入到新 html 文件中
 *  1.1 读取源 html 文件内容
 *  1.2 正则替换字符串
 *  1.3 写入到新的 html 文件中
 */
const fs = require('fs');
const path = require('path');

fs.readFile(path.join(__dirname, 'public/index.html'), (err, data) => {
  if (err) {
    console.log(err);
    return;
  }
  // console.log(`原始代码:${data.toString()}`);
  const result = data.toString().replace(/[\r\n]/g, '');
  // console.log(`压缩后的代码:${result}`);

  fs.writeFile(path.join(__dirname, 'dist/index.html'), result, (err) => {
    if (err) {
      console.log(err);
      return;
    }
    console.log('压缩成功');
  });
});

// ❯ node .\04.compress-html\build.js
// 压缩成功

小结 ​

  1. 前端工程化的理解?

    • 对前端代码进行优化,集成各种提高前端开发效率的工具等

认识 URL 中的端口号 ​

认识 URL 中端口号的作用,以及 Web 服务的作用

  1. URL 是统一资源定位符,简称网址,用于访问网络上的资源
  2. 端口号的作用:标记服务器里对应的服务程序,值为(0-65535 之间的任意整数)
  3. 注意:HTTP 协议,默认访问的是 80 端口
  4. Web 服务:一个程序,用于提供网上信息浏览功能
  5. 注意:0-1023 和一些特定的端口号被占用,我们自己编写服务程序请避开使用

小结 ​

  1. 端口号的作用?

    • 标记区分服务器里不同的服务程序
  2. 什么是 Web 服务?

    • 提供网上信息浏览的服务的一个程序

HTTP 模块 - 创建 Web 服务 ​

基于 Node.js 环境,使用内置 http 模块,创建 Web 服务程序

  1. 需求:引入 http 模块,使用相关语法,创建 Web 服务程序,响应返回给请求方一句提示 'hello,world'

  2. 步骤:

    • 引入 http 模块,创建 Web 服务对象
    • 监听 request 请求事件,对本次请求,做一些响应处理
    • 启动 Web 服务监听对应端口号
    • 运行本服务在终端进程中,用浏览器发起请求
  3. 注意:本机的域名叫做 localhost

js
/**
 * 目标:基于 `http` 模块创建 Web 服务程序
 *  1.1 加载 `http` 模块,创建 Web 服务对象
 *  1.2 监听 request 请求事件,设置响应头和响应体
 *  1.3 配置端口号并启动 Web 服务
 *  1.4 浏览器请求(http://localhost:13000)测试
 */

const http = require('http');
const server = http.createServer();

server.on('request', (req, res) => {
  // 设置响应头
  res.setHeader('Content-Type', 'text/html;charset=utf-8');
  // 设置响应体
  res.end('<h1>hello world</h1>' + '<p>欢迎使用 Node.js 和 <code>http</code> 模块创建的 Web 服务</p>');
});

server.listen(13000, () => {
  console.log('server running at http://localhost:13000');
  console.log('Web 服务启动成功了');
});

// ❯ node .\05.http-server.js
// server running at http://localhost:13000
// Web 服务启动成功了

// ❯ curl http://localhost:13000
// <h1>hello world</h1><p>欢迎使用 Node.js 和 <code>http</code> 模块创建的 Web 服务</p>

小结 ​

  1. 如何访问本机里运行的 Web 服务?

    • http://localhost:Web服务的端口号/资源路径

案例 - 浏览时钟 ​

体验 Web 服务除了接口数据以外,还能返回网页资源等

  1. 需求:基于 Web 服务,开发提供网页资源的功能,了解下后端的代码工作过程

    3bb429f4-7511-4cb4-9b87-944dc5cb3f3a

  2. 步骤:

    • 基于 http 模块,创建 Web 服务
    • 使用 req.url 获取请求资源路径为 /index.html 的时候,读取 04.compress-html/dist/index.html 文件内容字符串返回给请求方
    • 其他路径,暂时返回不存在的提示
    • 运行 Web 服务,用浏览器发起请求
案例 - 浏览时钟
js
/**
 * 目标:基于 Web 服务,开发提供网页资源的功能
 * 步骤:
 *  1. 基于 `http` 模块,创建 Web 服务
 *  2. 使用 req.url 获取请求资源路径,并读取 `04.compress-html/dist/index.html` 里字符串内容返回给请求方
 *  3. 其他路径,暂时返回不存在提示
 *  4. 运行 Web 服务,用浏览器发起请求
 */

const fs = require('fs');
const path = require('path');
const http = require('http');
const server = http.createServer();

server.on('request', (req, res) => {
  // 设置响应头
  res.setHeader('Content-Type', 'text/html;charset=utf-8');

  // 读取文件内容
  if (req.url === '/' || req.url === '/index.html') {
    fs.readFile(path.join(__dirname, '04.compress-html/dist/index.html'), 'utf-8', (err, data) => {
      if (err) {
        res.end('<h1>读取文件失败了</h1>');
      } else {
        res.end(data);
      }
    });
  } else {
    res.end('<h1>404 Not Found</h1>');
  }
});

server.listen(13000, () => {
  console.log('server running at http://localhost:13000');
  console.log('Web 服务启动成功了');
});

// ❯ node .\06.http-server-with-resource.js
// server running at http://localhost:13000
// Web 服务启动成功了

// ❯ curl http://localhost:13000
// <!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  ......

小结 ​

  1. Web 服务程序都有什么功能?

    • 提供数据和网页资源等等功能,其他它的功能远不止于此