Getting Started with Node.js - the path module

1 Introduction

The content of this article comes from bilibili dark horse programmers

2 What is the path module

The path module is a module officially provided by Node.js to process paths. It provides a series of methods and properties to meet users' needs for path processing.

3 path related methods

3.1 path.join()

Used to concatenate multiple path fragments into a complete path string

// path.join([...paths])

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

// 注意, '../' 会抵消上一层路径
// const pathStr = path.join('/a', '/b/c', '../', 'd', 'e')
// console.log(pathStr); // '/a/b/d/e'

const pathStr = path.join('/a', '/b/c', '../../', 'd', 'e')
console.log(pathStr); // '/a/d/e'

// fs.readFile(__dirname + '/files/1.txt')
// fs.readFile(__dirname + './files/1.txt') // 报错,会将 . 拼接到路径上
fs.readFile(path.join(__dirname, './files/1.txt'), 'utf-8', (err, data) => {
    
    
  if (err) {
    
    
    console.log('读取文件失败', err);
    return
  }
  console.log(data);
})

3.2 path.basename()

Used to parse the file name from the path string

// path.basename(path[, ext])

const path = require('path')

// 定义文件的存放路径
const fpath = '/a/b/c/index.html'

// const basename = path.basename(fpath)
// console.log(basename); // 'index.html

const basename = path.basename(fpath, '.html')
console.log(basename); // 'index'

3.3 path.extname()

Used to parse the suffix name from the path string

// path.extname(path)

const path = require('path')

// 定义文件的存放路径
const fpath = '/a/b/c/index.html'

const extname = path.extname(fpath)
console.log(extname); // '.html

4 comprehensive

Split the following HTML files into three files: index.html, index.css, and index.js, and store the three files in the files folder

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    body{
      
      
      background-color: red;
    }
  </style>
</head>
<body>
  <h3>welcome to my channel</h3>

  <script>
    setTimeout(() => {
      
      
      console.log('welcome to my channel');
    }, 3000);
  </script>
</body>
</html>

4.1 Implementation steps

  1. Create two regular expressions to match <style>and <script>tags respectively
  2. Use the fs module to read HTML files that need to be processed
  3. Customize the resolveCss method to write the index.css file
  4. Customize the resolveJs method to write the index.js file
  5. Customize the resolveHtml method to write the index.html file

4.2 Complete code

// 1.1 导入 fs 模块
const fs = require('fs')
// 1.2 导入 path 模块
const path = require('path')

// 1.3 匹配 <style></style> 标签的正则
// /s:匹配空白字符 /S:匹配非空白字符 *:匹配任意次
const regStyle = /<style>[\s\S]*<\/style>/
// 1.4 匹配 <script></script> 标签的正则
const regScript = /<script>[\s\S]*<\/script>/

// 2.1 调用 fs.readFile() 方法读取文件
fs.readFile(path.join(__dirname, './index.html'), 'utf-8', (err, dataStr) => {
    
    
  // 2.2 读取 HTML 文件失败
  if (err) return console.log('读取文件失败', err);
  // 2.3 读取 HTML 文件成功,调用对应的三个方法
  resolveCss(dataStr)
  resolveJs(dataStr)
  resolveHtml(dataStr)
})

// 3.1 处理 css 样式
const resolveCss = (htmlStr) => {
    
    
  // 3.2 使用正则提取页面中的 <style></style> 标签
  const r1 = regStyle.exec(htmlStr)
  // 3.3 将提取出来的 css 字符串做进一步的处理
  const newCss = r1[0].replace('<style>', '').replace('</style>', '')
  // 3.4 将处理好的 css 字符串写入 index.css 文件中 
  fs.writeFile(path.join(__dirname, './files/index.css'), newCss, err => {
    
    
    if (err) return console.log('写入文件失败', err);
    console.log('写入文件成功');
  })
}

// 4.1 处理 js
const resolveJs = (htmlStr) => {
    
    
  // 3.2 使用正则提取页面中的 <script></script> 标签
  const r1 = regScript.exec(htmlStr)
  // 3.3 将提取出来的 js 字符串做进一步的处理
  const newJs = r1[0].replace('<script>', '').replace('</script>', '')
  // 3.4 将处理好的 js 字符串写入 index.js 文件中 
  fs.writeFile(path.join(__dirname, './files/index.js'), newJs, err => {
    
    
    if (err) return console.log('写入文件失败', err);
    console.log('写入文件成功');
  })
}

// 5.1 处理 html
const resolveHtml = (htmlStr) => {
    
    
  // 5.2 将内嵌的 style 和 script 标签替换成内联的 link 和 script 标签
  const newHtml = htmlStr.replace(regStyle, '<link rel="stylesheet" href="./index.css" />').replace(regScript, '<script src="./index.js"></script>')
  // 5.3 写入 index.html 文件
  fs.writeFile(path.join('./files/index.html'), newHtml, err => {
    
    
    if (err) return console.log('写入文件失败', err);
    console.log('写入文件成功');
  })
}

4.3 Precautions

  1. fs.writeFile() can only be used to create files, not paths
  2. Repeatedly calling fs.writeFile() to write to the same file, the newly written content will overwrite the previous old content

Guess you like

Origin blog.csdn.net/weixin_36757282/article/details/128255619