search
HomeWeb Front-endJS TutorialAn article to talk about the fs file module and path module in Node (case analysis)

This article uses the case of reading and writing files and processing paths to learn about the fs file module and path module in Node. I hope it will be helpful to everyone!

An article to talk about the fs file module and path module in Node (case analysis)

1. fs file system module

fs module is Node. js Officially provided module for manipulating files. It provides a series of methods and properties to meet user requirements for file operations. [Related tutorial recommendations: nodejs video tutorial]

1. Read the specified file

##fs. readFile(): Read the contents of the specified file

Parameter 1: Required parameter, string, indicating the path of the file

Parameter 2: Optional parameter, indicating what Encoding format to read the file
Parameter 3: Required parameter. After the file reading is completed, the read result is obtained through the callback function

fs.readFile(path, [options], callback)

Example 1: Read demo.txt file

An article to talk about the fs file module and path module in Node (case analysis)

##demo.txt file

'前端杂货铺'

app.js File

// 导入 fs 文件系统模块
const fs = require('fs')

// 读取文件 utf-8 为中文编码格式
fs.readFile('../files/demo.txt', 'utf-8', function (err, data) {
    console.log('err:', err)
    console.log('data:', data)
})

An article to talk about the fs file module and path module in Node (case analysis)

Note: If you write the wrong path, that is, the file reading fails, the printed content is as follows [err is the error object, data is undefined]

An article to talk about the fs file module and path module in Node (case analysis)

Example 2: Determine whether reading the demo.txt file is successful

app.js file

Intentional wrong path, reading failed
  • The failure result is as follows
  • // 导入 fs 模块
    const fs = require('fs')
    
    // 读取文件
    fs.readFile('../files/demo1.txt', 'utf-8', function (err, data) {
        if(err) {
            return console.log('读取文件失败', err.message)
        }
        console.log('data:', data)
    })

An article to talk about the fs file module and path module in Node (case analysis)

2. Write the specified file

fs.writeFile(): Write content to the specified file

Parameter 1: Required parameter, you need to specify a string of file path, indicating the storage path of the file
Parameter 2: Required parameter, indicating the content to be written

Parameter 3: Yes Select the parameter to indicate the format in which the file content is written. The default is utf-8
Parameter 4: Required parameter, the callback function after the file writing is completed

fs.writeFile(file, data, [options], callback)

Example 1: Write demo.txt file

An article to talk about the fs file module and path module in Node (case analysis)##demo.txt file

// 该文件内容为空
app.js file

// 导入 fs 文件系统模块
const fs = require('fs')

// 写入文件内容
fs.writeFile('../files/demo.txt', '这里是前端杂货铺', function(err, data) {
    if (err) {
        return console.log('写入文件失败', err.message)
    }
    console.log('文件写入成功')
})

An article to talk about the fs file module and path module in Node (case analysis)Note: If writing to a disk that does not exist, the file writing fails and the printed content is as follows

An article to talk about the fs file module and path module in Node (case analysis)

3. Cases of organizing resultsExample: format conversion of results

Grade format before conversion

An article to talk about the fs file module and path module in Node (case analysis)Grade format after conversion

The file format is as followsAn article to talk about the fs file module and path module in Node (case analysis)

An article to talk about the fs file module and path module in Node (case analysis)score.txt file

Write the score Content

    杂货铺=100 张三=98 李四=95 王五=92
  • app.js file

    Import the required fs file module

      Use the fs.readFile() method, Read the score.txt file in the material directory
    • Determine whether the file reading fails
    • After the file is read successfully, process the score data
    • The completed score data will be processed. Call the fs.writeFile() method to write to the new file newScore.txt
    • // 导入 fs 文件系统模块
      const fs = require('fs')
      
      // 写入文件内容
      fs.readFile('../files/score.txt', 'utf-8', function (err, data) {
          // 判断是否读取成功
          if (err) {
              return console.log('读取文件失败' + err.message)
          }
          // 把成绩按空格进行分割
          const arrOld = data.split(' ')
          // 新数组的存放
          const arrNew = []
          // 循环分割后的数组 对每一项数据 进行字符串的替换操作
          arrOld.forEach(item => {
              arrNew.push(item.replace('=', ':'))
          })
          // 把新数组中的每一项合并 得到新的字符串
          const newStr = arrNew.join('\r\n')
      
          // 写入新数据
          fs.writeFile('../files/newScore.txt', newStr, function (err) {
              if (err) {
                  return console.log('写入成绩失败' + err.message)
              }
              console.log('成绩写入成功')
          })
      })

    An article to talk about the fs file module and path module in Node (case analysis)

    An article to talk about the fs file module and path module in Node (case analysis)

    ##4. Processing path

    __dirname: Indicates the directory where the current file is located

    Example: Write relative path

    const fs = require('fs')
    
    fs.readFile('../files/score.txt', 'utf-8', function(err, data) {
        if (err) {
            return console.log('文件读取失败' + err.message)
        }
        console.log('文件读取成功')
    })

    An article to talk about the fs file module and path module in Node (case analysis)

    示例:使用 __dirname

    An article to talk about the fs file module and path module in Node (case analysis)

    const fs = require('fs')
    
    // 读取文件
    fs.readFile(__dirname + '/files/score.txt', 'utf-8', function(err, data) {
        if (err) {
            return console.log('文件读取失败' + err.message)
        }
        console.log('文件读取成功')
    })

    An article to talk about the fs file module and path module in Node (case analysis)

    二、path 路径模块

    path 模块是 Node.js 官方提供的、用来处理路径的模块

    1、path.join() 路径拼接

    path.join():用来将多个路径判断拼接成一个完整的路径字符串

    参数:…paths <string></string> 路径片段的序列
    返回值:返回值 <string></string>

    path.join([...paths])

    示例:路径拼接

    // 导入 path 模块
    const path = require(&#39;path&#39;)
    // ../ 会抵消前面的路径
    const pathStr = path.join(&#39;/a&#39;,&#39;/b/c&#39;, &#39;../&#39;, &#39;./d&#39;, &#39;e&#39;)
    console.log(pathStr)

    An article to talk about the fs file module and path module in Node (case analysis)
    备注:涉及到路径拼接的操作,都要使用 path.join() 方法进行处理。不要直接用 + 进行字符串拼接

    示例:使用 path 进行路径拼接

    const fs = require(&#39;fs&#39;)
    const path = require(&#39;path&#39;)
    
    // 文件读取
    fs.readFile(path.join(__dirname, &#39;/files/score.txt&#39;), &#39;utf-8&#39;, function(err, data) {
        if (err) {
            return console.log(&#39;文件读取失败&#39;, err.message)
        }
        console.log(&#39;文件读取成功&#39;)
    })

    An article to talk about the fs file module and path module in Node (case analysis)

    2、path.basename() 解析文件名

    path.basename():用来从路径字符串中,将文件名解析出来

    参数 1:path 必选参数,表示一个路径的字符串
    参数 2:ext 可选参数,表达文件扩展名
    返回值:返回 表示路径中的最后一部分

    path.basename(path, [ext])

    示例:解析路径,去除扩展名

    // 导入 path 模块
    const path = require(&#39;path&#39;)
    // 文件的存放路径
    const fpath = &#39;/a/b/c/index.html&#39;
    
    // 将文件名解析出来
    const fullName = path.basename(fpath)
    console.log(fullName) // 输出 index.html
    
    // 去除扩展名
    const nameWithoutExt = path.basename(fpath, &#39;.html&#39;)
    
    console.log(nameWithoutExt) // 输出 index

    An article to talk about the fs file module and path module in Node (case analysis)

    3、path.extname() 获取扩展名

    path.extname():可以获取路径中的扩展名部分

    参数:path <string></string> 必选参数,表示一个路径的字符串
    返回值:返回 <string></string> 返回得到的扩展名字符串

    path.extname(path)

    示例:获取扩展名

    // 导入 path 模块
    const path = require('path')
    // 文件的存放路径
    const fpath = '/a/b/c/index.html'
    // 获取扩展名
    const fext = path.extname(fpath)
    
    console.log(fext) // .html

    An article to talk about the fs file module and path module in Node (case analysis)

    更多node相关知识,请访问:nodejs 教程

    The above is the detailed content of An article to talk about the fs file module and path module in Node (case analysis). For more information, please follow other related articles on the PHP Chinese website!

  • Statement
    This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
    JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

    Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

    Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

    JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

    Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

    I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

    How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

    This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

    JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

    JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

    The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

    The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

    Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

    JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

    Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

    Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools