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 服务已启动')
})

相关推荐

  1. node.js 基础

    2024-06-06 14:02:01       12 阅读
  2. <span style='color:red;'>nodejs</span>

    nodejs

    2024-06-06 14:02:01      15 阅读
  3. <span style='color:red;'>nodejs</span>

    nodejs

    2024-06-06 14:02:01      11 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-06 14:02:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-06 14:02:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-06 14:02:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-06 14:02:01       20 阅读

热门阅读

  1. 前端预览pdf文件(后端返回pdf文件流)

    2024-06-06 14:02:01       8 阅读
  2. react高阶组件——withRouter

    2024-06-06 14:02:01       10 阅读
  3. vue中SKU实现

    2024-06-06 14:02:01       7 阅读
  4. 2024前端面试准备-HTML&CSS

    2024-06-06 14:02:01       10 阅读
  5. 深度学习中训练集、验证集和测试集的不同作用

    2024-06-06 14:02:01       9 阅读
  6. Linux学习—Linux服务和守护进程

    2024-06-06 14:02:01       8 阅读
  7. Overall timing accuracy 和Edge placement accuracy 理解

    2024-06-06 14:02:01       8 阅读
  8. flutter 适配屏幕宽高工具

    2024-06-06 14:02:01       10 阅读
  9. 通过nginx弄一个滑块加图片的人机验证

    2024-06-06 14:02:01       10 阅读
  10. 渗透测试之Web安全系列教程(二)

    2024-06-06 14:02:01       8 阅读