Node.js基础

本节内容

  • 介绍
  • 安装
  • hello world
  • fs模块
  • path模块
  • http模块
  • 案例-压缩前端代码
  • http模块
  • 案例-浏览时钟

介绍

Node.js是一个跨平台JavaScript运行环境, 使开发者可以搭建服务端的JavaScript应用程序

作用

  • 编写数据接口, 提供网页资源浏览功能
  • 前端工程化, 后续的Vue和React框架都是工程化项目

工程化

项目从开发到上线, 把这个过程中的所有工具和技术集中管理, 称为前端工程化

Node.js是前端工程化的基础(因为Node.js可以主动读取前端代码的内容)

宿主环境

浏览器能执行JS代码, 是因为浏览器内核中集成了V8引擎(C++程序)

Node.js能执行JS代码, 是因为Node.js是基于V8引擎开发出来的(运行环境)

相同点

  1. 浏览器和Node.js都可以作为JS的宿主环境
  2. 都支持ECMAScript标准语法

不同点

  1. Node.js环境不存在DOM和BOM
  2. Node.js有独立的API

安装

官网 Node.js --- Run JavaScript Everywhere

  1. 官网下载安装包(或资料中提供), 傻瓜式安装即可

  2. 本课程使用16.19.0版本 (兼容vue-admin-template)

  3. 不要安装在中文路径下

  4. 不要勾选自动安装其他配套软件

  5. 成功验证: cmd终端 -> 执行 node -v 查看版本号

hello world

复制代码
for (let i = 0; i < 5; i++) {
  console.log('hello world' + i)
}
  1. 新建hello.js文件, 编写代码,
  2. 打开命令行窗口
  3. 命令 node xxx.js + 回车执行

fs模块

封装了与本机文件系统进行交互的方法和属性

复制代码
// 加载模块
const fs = require('fs')

// 写入文件
// 可以自动创建文件, 但是不会自动创建文件夹
fs.writeFile('./02test.txt', 'hrllo,world', (err) => {
  if (err) console.log(err)
  else console.log('写入成功')
})

// 读取文件
fs.readFile('./02test.txt', (err, data) => {
  // data是 buffer 类型的数据, 16进制数据流对象
  // .toString() 转换成字符串
  if (err) console.log(err)
  else console.log(data.toString())
})

path模块

Node.js代码中,相对路径是根据终端所在路径来查找的, 可能无法找到你想要的文件

绝对路径

  • 在Node.js中, 建议使用绝对路径, 使代码更加健壮

  • __dirname内置,可以获取当前文件所在文件夹的绝对路径

  • windows和mac的文件路径稍有区别

  • path.join() 可以抹平平台差异, 它会使用特定平台的分隔符, 作为定界符, 将所有给定的路径片段连接在一起

复制代码
/**
 * 目标:在 Node.js 环境的代码中,应使用绝对路径
 * 原因:代码的相对路径是以终端所在文件夹为起点,而不是 Vscode 资源管理器
 *  容易造成目标文件找不到的错误
 */
const fs = require('fs')
// 1,引入 path 模块对象
const path = require('path')
// 2, 使用__dirname获取当前文件的绝对路径
// 3, 使用 path.join() 方法拼接目标文件的绝对路径
fs.readFile(path.join(__dirname, '../02test.txt'), (error, data) => {
  if (error) console.log(error)
  else console.log(data.toString())
})

案例-压缩前端代码

复制代码
/**
 * 目标1:压缩 html 代码
 * 需求:把回车符 \r,换行符 \n 去掉,写入到新 html 文件中
 *  1.1 读取源 html 文件内容
 *  1.2 正则替换字符串
 *  1.3 写入到新的 html 文件中
 *  1.4 运行压缩完的代码,验证成功
 */
const fs = require('fs')
const path = require('path')

fs.readFile(path.join(__dirname, 'public/index.html'), (error, data) => {
  if (error) console.log(error)
  else {
    const htmlStr = data.toString()
    const newHtmlStr = htmlStr.replace(/[\r\n]/g, '')

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

http模块

使用http模块创建服务器程序

复制代码
/**
 * 目标:基于 http 模块创建 Web 服务程序
 *  1.1 加载 http 模块,创建 Web 服务对象
 *  1.2 监听 request 请求事件,设置响应头和响应体
 *  1.3 配置端口号并启动 Web 服务
 *  1.4 浏览器请求(http://localhost:3000)测试
 */
// 引入模块
const http = require('http')
// 创建服务
const server = http.createServer()
// 监听请求
server.on('request', (req, res) => {
  // 设置响应头
  // 内容类型: 普通文本  编码格式: utf-8
  res.setHeader('Content-Type', 'text/html;charset=utf-8')
  // 设置响应体
  res.end('你好, 欢迎访问我的web程序')
})

// 配置端口号并启动 Web 服务
server.listen(3000, () => {
  console.log('web服务启动')
})

案例-浏览时钟

基于web服务, 开发提供网页资源的功能

复制代码
/**
 * 目标:基于 Web 服务,开发提供网页资源的功能
 * 步骤:
 *  1. 基于 http 模块,创建 Web 服务
 *  2. 使用 req.url 获取请求资源路径,并读取 index.html 里字符串内容返回给请求方
 *  3. 其他路径,暂时返回不存在提示
 *  4. 运行 Web 服务,用浏览器发起请求
 */
// 导入模块
const http = require('http')
const path = require('path')
const fs = require('fs')
// 创建服务
const server = http.createServer()
// 监听服务
// req 请求对象
// res 响应对象
server.on('request', (req, res) => {
  if (req.url === '/index.html') {
    // 读取文件
    fs.readFile(path.join(__dirname, 'dist/index.html'), (error, data) => {
      if (error) console.log(error)
      else {
        // 设置响应内容类型为 超文本(html) 编码格式为 utf-8
        res.setHeader('Content-Type', 'text/html;charset=utf-8')
        // 响应资源
        res.end(data.toString())
      }
    })

  } else {
    // 设置响应内容类型为 超文本(html) 编码格式为 utf-8
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    // 响应资源
    res.end('请求资源不存在 404')

  }

})
// 注册端口,启动服务
server.listen(8080, () => {
  console.log('web 服务已启动')
})
相关推荐
cpolar技术支持12 小时前
把 agent-autoloop 装在 Mac 上:用本机 Node 实跑一次「接活—提问—拍板—接着干」,再用 cpolar 把它的状态页开给不在工位的自己
node.js·内网穿透·cpolar·ai agent·agent-autoloop
SEO_juper18 小时前
Node.js 全站 SEO 体检报告生成器:一次查完标题、描述、canonical、H1、图片
开发语言·前端·node.js·html·bash
木头左2 天前
【Node.js】Markdown 转带图片 Word 文档实战:docx 库转换器设计与 5 个踩坑
node.js·word·markdown·文档自动化
思特奇时空智能2 天前
大规模点要素地图渲染性能优化实践
vue.js·arcgis·性能优化·node.js·html·gis·webgl
w3296362714 天前
飞书接单到月度结算:我用一个 DSH 插件跑通鞋类采购 WMS,附 22 项验收
pdf·node.js·飞书·后端开发·ai agent
濮水大叔4 天前
Cabloy/Vona 为什么不需要 NestJS 的 Dynamic Module
typescript·node.js·nestjs
匠云创新5 天前
读完一万段要两分钟:我们把标书读取从 WPS 对象模型搬到了 docx 解析
性能优化·node.js
某哈压力大5 天前
SSH 突然 Connection reset?不是密钥坏了,是 OpenSSL 把 sshd 干趴了
前端·node.js·命令行
回眸&啤酒鸭5 天前
【回眸】Node.js 新手从零到一实战指南
node.js
浪遏5 天前
recruitment-cli:让 AI 接手求职招聘,从架构到一次发送超时
架构·typescript·node.js