search
HomeWeb Front-endJS TutorialLet's talk about the fs module and path module in node

This article will take you through the fs file system module and path module in node. I hope it will be helpful to you!

Let's talk about the fs module and path module in node

fs file system module

fs module is officially provided by Node.js and is used for operation File module. It provides a series of methods and properties to meet users' file operation needs.

  • fs.readFile() method, used to read the content in the specified file
  • fs.writeFile() method, used to write the content to the specified file. If you want In JavaScript code, if you use the fs module to operate files, you need to import it first as follows:
 const fs = reuire('fs')

Read the contents of the specified file

1. The syntax format of fs.readFile()

Using the fs.readFile() method, you can read the content in the specified file. The syntax format is as follows:

 fs.readFile(path[, options], callback)
  • Parameter 1: Required parameter, you need to specify a string of file path, indicating which path corresponds to the file to be read.
  • Parameter 2: Optional parameter, indicating the encoding format to read the file.
  • Parameter 3: Required parameter. After the file reading is completed, the reading result is obtained through the callback function.

2. Sample code of fs.readFile()

Read the contents of the specified file in utf8 format, and print the values ​​of err and data :

 const fs = require('fs');
 fs.readFile('hello.txt', 'utf-8', (err, data) => {
     // 判断是否读取成功
     if (err) return console.log(err);
     console.log(data); 
 });

Write content to the specified file

##1. Syntax format of fs.writeFile()

Use the fs.writeFile() method to write content to the specified file. The syntax format is as follows:

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

    Parameter 1: Required parameter, you need to specify a file path A string representing the storage path of the file.
  • Parameter 2: Required parameter, indicating the content to be written.
  • Parameter 3: Optional parameter, indicating the format in which to write the file content. The default value is utf8.
  • Parameter 4: Required parameter, callback function after file writing is completed.

2. Sample code for fs.writeFile()

 const fs = require('fs');
 fs.writeFile('./hello.txt', 'hello node', (err) => {
     // 判断是否写入成功
     if (err) return console.log(err);
     console.log('写入成功');
 });

Read the names of all files in the specified directory

1. The syntax format of fs.readdir()

Using the fs.readdir() method, you can read the names of all files in the specified directory. The syntax format is as follows:

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

    Parameter 1: Required parameter, indicating the file name list in which directory to read.
  • Parameter 2: Optional parameter, in what format to read the file name in the directory, the default value is utf8.
  • Parameter 3: Required parameter, callback function after reading is completed.

2. Sample code of fs.readdir()

Through the fs.readdir() method, you can read the names of all files in the specified directory :

 const fs = require('fs');
 fs.readdir('./', (err, data) => {
     // 错误处理
     if (err) return console.log(err);
     console.log(data);
 });

fs module-path dynamic splicing problem

When using the fs module to operate files, if the provided operation path starts with . When the relative path starts with / or ../, it is easy to cause dynamic path splicing errors. This is because when the code is running, the full path of the file being operated will be dynamically spliced ​​from the directory where the node command is executed.

Solution: When using the fs module to operate files, provide absolute paths directly instead of relative paths starting with ./ or ../ to prevent dynamic path splicing problems.

Note: Use __dirname to get the absolute path of the current file

 const fs = require('fs');
 // 拼接要读取文件的绝对路径
 let filepath = __dirname +'/hello.txt'
 fs.readFile(filepath, 'utf-8', (err, data) => {
     // 判断是否读取成功
     if (err) return console.log(err);
     console.log(data); 
 });

path path module

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

    path.join() method, used to splice multiple path fragments into a complete path string
  • path.basename() method, used to convert path strings from , parse the file name out
If you want to use the path module to process paths in JavaScript code, you need to import it first in the following way:

 const path = require('path')

Path splicing

The syntax format of path.join()

Use the path.join() method to combine multiple paths The fragments are spliced ​​into a complete path string. The syntax format is as follows:

 path.join([...paths])

Use the path.join() method to splice multiple path fragments into a complete path string:

 const path = require('path');
 console.log( path.join('a', 'b', 'c') ); // a/b/c
 console.log( path.join('a', '/b/', 'c') ); // a/b/c
 console.log( path.join('a', '/b/', 'c', 'index.html') ); // a/b/c/index.html
 console.log( path.join('a', 'b', '../c', 'index.html') ); // a/c/index.html
 console.log(__dirname); // node自带的全局变量,表示当前js文件所在的绝对路径
 // 拼接成绩.txt的绝对路径
 console.log( path.join(__dirname, '成绩.txt') ); // ------ 最常用的

Get the file name in the path

1. The syntax format of path.basename()

Use path.basename( ) method, you can get the last part of the path. You often use this method to get the file name in the path. The syntax format is as follows:

 path.basename(path[,ext])

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

2.path.basename()的代码示例

使用 path.basename() 方法,可以从一个文件路径中,获取到文件的名称部分:

 // 找文件名
 console.log( path.basename('index.html') ); // index.html
 console.log( path.basename('a/b/c/index.html') ); // index.html
 console.log( path.basename('a/b/c/index.html?id=3') ); // index.html?id=3
 console.log(path.basename('/api/getbooks')) // getbooks

获取路径中的文件扩展名

1.path.extname()的语法格式

使用 path.extname() 方法,可以获取路径中的扩展名部分,语法格式如下:

 path.extname(path)
  • path 必选参数,表示一个路径的字符串
  • 返回:  返回得到的扩展名字符串

使用 path.extname() 方法,可以获取路径中的扩展名部分

 // 找字符串中,最后一个点及之后的字符
 console.log( path.extname('index.html') ); // .html
 console.log( path.extname('a.b.c.d.html') ); // .html
 console.log( path.extname('asdfas/asdfa/a.b.c.d.html') ); // .html
 console.log( path.extname('adf.adsf') ); // .adsf

原文地址:https://juejin.cn/post/7088650568150810638

作者:L同学啦啦啦

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

The above is the detailed content of Let's talk about the fs module and path module in node. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.