


An 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!
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 fileParameter 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 functionfs.readFile(path, [options], callback)Copy after login
Example 1: Read demo.txt 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)
})
Example 2: Determine whether reading the demo.txt file is successful
app.js fileIntentional 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) })
Copy after login
2. Write the specified file
fs.writeFile(): Write content to the specified fileParameter 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 writtenParameter 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 completedfs.writeFile(file, data, [options], callback)Copy after login
Example 1: Write demo.txt file
##demo.txt file
// 该文件内容为空
// 导入 fs 文件系统模块 const fs = require('fs') // 写入文件内容 fs.writeFile('../files/demo.txt', '这里是前端杂货铺', function(err, data) { if (err) { return console.log('写入文件失败', err.message) } console.log('文件写入成功') })
Note: If writing to a disk that does not exist, the file writing fails and the printed content is as follows
3. Cases of organizing resultsExample: format conversion of results
Grade format before conversion
Grade format after conversion
The file format is as follows
score.txt file
Write the score Content
杂货铺=100 张三=98 李四=95 王五=92
Import the required fs file module
- Use the fs.readFile() method, Read the score.txt file in the material directoryDetermine whether the file reading failsAfter the file is read successfully, process the score dataThe 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('成绩写入成功') }) })
__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('文件读取成功') })
示例:使用 __dirname
const fs = require('fs') // 读取文件 fs.readFile(__dirname + '/files/score.txt', 'utf-8', function(err, data) { if (err) { return console.log('文件读取失败' + err.message) } console.log('文件读取成功') })
二、path 路径模块
path 模块是 Node.js 官方提供的、用来处理路径的模块
1、path.join() 路径拼接
path.join():用来将多个路径判断拼接成一个完整的路径字符串
参数:…paths
<string>
路径片段的序列
返回值:返回值<string>
path.join([...paths])
示例:路径拼接
// 导入 path 模块 const path = require('path') // ../ 会抵消前面的路径 const pathStr = path.join('/a','/b/c', '../', './d', 'e') console.log(pathStr)
备注:涉及到路径拼接的操作,都要使用 path.join() 方法进行处理。不要直接用 + 进行字符串拼接
示例:使用 path 进行路径拼接
const fs = require('fs') const path = require('path') // 文件读取 fs.readFile(path.join(__dirname, '/files/score.txt'), 'utf-8', function(err, data) { if (err) { return console.log('文件读取失败', err.message) } console.log('文件读取成功') })
2、path.basename() 解析文件名
path.basename():用来从路径字符串中,将文件名解析出来
参数 1:path 必选参数,表示一个路径的字符串
参数 2:ext 可选参数,表达文件扩展名
返回值:返回 表示路径中的最后一部分
path.basename(path, [ext])
示例:解析路径,去除扩展名
// 导入 path 模块 const path = require('path') // 文件的存放路径 const fpath = '/a/b/c/index.html' // 将文件名解析出来 const fullName = path.basename(fpath) console.log(fullName) // 输出 index.html // 去除扩展名 const nameWithoutExt = path.basename(fpath, '.html') console.log(nameWithoutExt) // 输出 index
3、path.extname() 获取扩展名
path.extname():可以获取路径中的扩展名部分
参数:
path <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
更多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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article will give you an in-depth understanding of the memory and garbage collector (GC) of the NodeJS V8 engine. I hope it will be helpful to you!

The Node service built based on non-blocking and event-driven has the advantage of low memory consumption and is very suitable for handling massive network requests. Under the premise of massive requests, issues related to "memory control" need to be considered. 1. V8’s garbage collection mechanism and memory limitations Js is controlled by the garbage collection machine

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

The file module is an encapsulation of underlying file operations, such as file reading/writing/opening/closing/delete adding, etc. The biggest feature of the file module is that all methods provide two versions of **synchronous** and **asynchronous**, with Methods with the sync suffix are all synchronization methods, and those without are all heterogeneous methods.

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

The event loop is a fundamental part of Node.js and enables asynchronous programming by ensuring that the main thread is not blocked. Understanding the event loop is crucial to building efficient applications. The following article will give you an in-depth understanding of the event loop in Node. I hope it will be helpful to you!

The reason why node cannot use the npm command is because the environment variables are not configured correctly. The solution is: 1. Open "System Properties"; 2. Find "Environment Variables" -> "System Variables", and then edit the environment variables; 3. Find the location of nodejs folder; 4. Click "OK".
