亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
2. Write the specified file" >2. Write the specified file
Example: format conversion of results" >3. Cases of organizing resultsExample: format conversion of results
__dirname: Indicates the directory where the current file is located" >__dirname: Indicates the directory where the current file is located
二、path 路徑模塊" >二、path 路徑模塊
1、path.join() 路徑拼接" >1、path.join() 路徑拼接
2、path.basename() 解析文件名" >2、path.basename() 解析文件名
3、path.extname() 獲取擴展名" >3、path.extname() 獲取擴展名
Home Web Front-end JS Tutorial 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)

Nov 18, 2022 pm 08:36 PM
nodejs? node.js node

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 文件系統(tǒng)模塊
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

// 該文件內(nèi)容為空
app.js file

// 導入 fs 文件系統(tǒng)模塊
const fs = require('fs')

// 寫入文件內(nèi)容
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 文件系統(tǒng)模塊
    const fs = require('fs')
    
    // 寫入文件內(nèi)容
    fs.readFile('../files/score.txt', 'utf-8', function (err, data) {
        // 判斷是否讀取成功
        if (err) {
            return console.log('讀取文件失敗' + err.message)
        }
        // 把成績按空格進行分割
        const arrOld = data.split(' ')
        // 新數(shù)組的存放
        const arrNew = []
        // 循環(huán)分割后的數(shù)組 對每一項數(shù)據(jù) 進行字符串的替換操作
        arrOld.forEach(item => {
            arrNew.push(item.replace('=', ':'))
        })
        // 把新數(shù)組中的每一項合并 得到新的字符串
        const newStr = arrNew.join('\r\n')
    
        // 寫入新數(shù)據(jù)
        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():用來將多個路徑判斷拼接成一個完整的路徑字符串

參數(shù):…paths <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():用來從路徑字符串中,將文件名解析出來

參數(shù) 1:path 必選參數(shù),表示一個路徑的字符串
參數(shù) 2:ext 可選參數(shù),表達文件擴展名
返回值:返回 表示路徑中的最后一部分

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():可以獲取路徑中的擴展名部分

參數(shù):path <string> 必選參數(shù),表示一個路徑的字符串
返回值:返回 <string> 返回得到的擴展名字符串

path.extname(path)

示例:獲取擴展名

// 導入 path 模塊
const path = require(&#39;path&#39;)
// 文件的存放路徑
const fpath = &#39;/a/b/c/index.html&#39;
// 獲取擴展名
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相關(guān)知識,請訪問: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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed graphic explanation of the memory and GC of the Node V8 engine Detailed graphic explanation of the memory and GC of the Node V8 engine Mar 29, 2023 pm 06:02 PM

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!

An article about memory control in Node An article about memory control in Node Apr 26, 2023 pm 05:37 PM

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

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

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

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

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!

Let's talk about the event loop in Node Let's talk about the event loop in Node Apr 11, 2023 pm 07:08 PM

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!

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

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!

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

Learn more about Buffers in Node Learn more about Buffers in Node Apr 25, 2023 pm 07:49 PM

At the beginning, JS only ran on the browser side. It was easy to process Unicode-encoded strings, but it was difficult to process binary and non-Unicode-encoded strings. And binary is the lowest level data format of the computer, video/audio/program/network package

See all articles