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 服务已启动')
})
  • 23
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值