【Node.js】入门 和 基本读写路径处理指令 以及 创建本地服务器

发布于:2025-08-19 ⋅ 阅读:(14) ⋅ 点赞:(0)

目录

一、fs 模块 - 读写文件

二、 path模块 - 路径处理

案例 - 压缩前端html

三、 URL中的端口号

四、 http模块 - 创建一个Web服务(设置一个本地服务器)

案例 - 时钟浏览

总结不易 ~ 本章节对我有很大收获, 希望对你也是!!!


本章节素材已上传至gitee:ajax_study: 这是ajax、Node.j学习的仓库 - Gitee.comhttps://gitee.com/liu-yihao-hhh/ajax_study/tree/master/nodejs

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

安装好nodejs后就可以直接在本地环境跑js代码了!

直接在本地运行js文件: node  + 文件名

一、fs 模块 - 读写文件

  • 模块:类似插件,封装了方法/属性
  • fs模块:封装了与本机文件系统进行交互的,方法/属性

加载fs模块对象

const fs = require('fs') // fs是模块标识符:模块的名字

写入文件内容

// 写入文件内容 writeFile('文件路径', '写入内容', err =>{}) // err 表示错误信息
fs.writeFile('文件路径', '写入内容', err => {})

 读取文件

// 3. 读取文件 fs.readFile('文件路径', (err, data) => {})
fs.readFile('./test.txt', (err, data) => {})
  // data是buffer16进制数据流对象
  // .toString() 转换成字符串

// 1. 加载fs模块对象
const fs = require('fs') // fs 是模块标识符:模块名字
// 2. 写入文件内容 writeFile('文件路径', '写入内容', err =>{}) // err 表示错误信息
fs.writeFile('./test.txt', 'hello, Node.js', (err) => {
  if (err) console.log(err)
  else console.log('写入成功')
})

// 3. 读取文件 fs.readFile('文件路径', (err, data) => {})
fs.readFile('./test.txt', (err, data) => {
  if (err) console.log(err)
  // data是buffer16进制数据流对象
  // .toString() 转换成字符串
  else console.log(data.toString())
})

二、 path模块 - 路径处理

建议:在Node.js代码中,使用绝对路径

补充:__dirname内置变量(获取当前模块目录-绝对路径)由于windows分隔符是'\',mac分隔符是'/'

__dirname 是 Node.js 提供的一个全局变量,表示当前这个 JS 文件所在的绝对目录路径

  • 比如你的文件是这个路径:C:\Users\lyhhh\Desktop\nodejs\04\build.js 
  • __dirname 的值就是:C:\Users\lyhhh\Desktop\nodejs\04

注意:path.join()会使用特定于平台的分隔符,将所有给定的路径片段连接在一起

const path = require('path')
path.join('路径1', '路径2', ……)

代码的相对路径是以终端所在文件夹为起点,而不是 Vscode 资源管理器,容易造成目标文件找不到的错误。其实也还行 就是从最外层开始的!!!

 

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

案例 - 压缩前端html

 需求:把回车符(\r) 和 换行符(\n)去掉后,写入新的html文件中

将代码进行压缩,利用正则表达式,来替换html里面所有的空格和换行为, ’‘空字符串,在写入新的html文件中

const fs = require('fs')
const path = require('path')

fs.readFile(path.join(__dirname, 'public/index.html'), (err, data) => {
  if (err) {
    console.log(err)
  } else {
    // 记得加 () 调用函数
    const htmlStr = data.toString()
    const resultStr = htmlStr.replace(/[\r\n]/g, '') // 去掉换行回车
    console.log(resultStr)
    // 1.3 写入到新的html文件中
    fs.writeFile(path.join(__dirname, 'dist/index.html'), resultStr, err => {
      if (err) console.log(err)
      else console.log('写入成功')
    })
  }
})

三、 URL中的端口号

URL:统一资源定位符,简称网址,用于访问服务器里的资源

常见的服务程序

  • Web 服务程序:用于提供网上信息浏览功能
  • 注意: 0-1023 和一些特定端口号被占用,我们自己编写服务程序请避开使用

四、 http模块 - 创建一个Web服务(设置一个本地服务器)

// 1.1 加载 http 模块,创建 Web 服务对象
const http = require('http')
const server = http.createServer()
// 1.2 监听 request 请求事件,设置响应头和响应体
server.on('request', (req, res) => {
  // 设置响应头-内容类型-普通文本以及中文编码格式
  res.setHeader('Content-Type', 'text/plain;charset=utf-8')
  // 设置响应体内容,结束本次请求与响应
  res.end('欢迎使用 Node.js 和 http 模块创建的 Web 服务')
})
// 1.3 配置端口号并启动 Web 服务
server.listen(3000, () => {
  console.log('Web 服务启动成功了')
})

本地访问

  • 如果你启动了一个本地服务器(例如在 localhost:3000),只有在同一台电脑或同一局域网内的设备才能通过这个地址访问。

  • 例如,在浏览器中访问 http://localhost:3000,你可以看到你的网页,但是别人无法直接通过这个地址访问。

案例 - 时钟浏览

获取dist文件夹内的index.html的文件进行读取并渲染到本地的服务器上

/**
 * 目标:基于 Web 服务,开发提供网页资源的功能
 * 步骤:
 *  1. 基于 http 模块,创建 Web 服务
 *  2. 使用 req.url 获取请求资源路径,并读取 index.html 里字符串内容返回给请求方
 *  3. 其他路径,暂时返回不存在提示
 *  4. 运行 Web 服务,用浏览器发起请求
 */
const fs = require('fs')
const path = require('path')
// 1. 基于 http 模块,创建 Web 服务
const http = require('http')
const server = http.createServer()
server.on('request', (req, res) => {
  // 2. 使用 req.url 获取请求资源路径,并读取 index.html 里字符串内容返回给请求方
  if (req.url === '/index.html') {
    fs.readFile(path.join(__dirname, 'dist/index.html'), (err, data) => {
      res.setHeader('Content-Type', 'text/html;charset=utf-8')
      res.end(data.toString())
    })
  } else {
    // 3. 其他路径,暂时返回不存在提示
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    res.end('你要访问的资源路径不存在')
  }
})
server.listen(8080, () => {
  console.log('Web 服务启动成功了')
})

总结不易 ~ 本章节对我有很大收获, 希望对你也是!!!


网站公告

今日签到

点亮在社区的每一天
去签到