Table of Contents
fs file system module
path path module
Home Web Front-end JS Tutorial Let's talk about the fs module and path module in node

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

Apr 24, 2022 pm 09:00 PM
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')
Copy after login

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)
Copy after login
  • 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); 
 });
Copy after login

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)
Copy after login

    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('写入成功');
 });
Copy after login

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)
Copy after login

    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);
 });
Copy after login

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); 
 });
Copy after login

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')
Copy after login

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])
Copy after login

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') ); // ------ 最常用的
Copy after login

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])
Copy after login
  • 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
Copy after login

获取路径中的文件扩展名

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

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

 path.extname(path)
Copy after login
  • 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
Copy after login

原文地址: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 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

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

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)

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!

How to delete node in nvm How to delete node in nvm Dec 29, 2022 am 10:07 AM

How to delete node with nvm: 1. Download "nvm-setup.zip" and install it on the C drive; 2. Configure environment variables and check the version number through the "nvm -v" command; 3. Use the "nvm install" command Install node; 4. Delete the installed node through the "nvm uninstall" command.

How to do Docker mirroring of Node service? Detailed explanation of extreme optimization How to do Docker mirroring of Node service? Detailed explanation of extreme optimization Oct 19, 2022 pm 07:38 PM

During this period, I was developing a HTML dynamic service that is common to all categories of Tencent documents. In order to facilitate the generation and deployment of access to various categories, and to follow the trend of cloud migration, I considered using Docker to fix service content and manage product versions in a unified manner. . This article will share the optimization experience I accumulated in the process of serving Docker for your reference.

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!

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

Let's talk about how to use pkg to package Node.js projects into executable files. Let's talk about how to use pkg to package Node.js projects into executable files. Dec 02, 2022 pm 09:06 PM

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

What to do if npm node gyp fails What to do if npm node gyp fails Dec 29, 2022 pm 02:42 PM

npm node gyp fails because "node-gyp.js" does not match the version of "Node.js". The solution is: 1. Clear the node cache through "npm cache clean -f"; 2. Through "npm install -g n" Install the n module; 3. Install the "node v12.21.0" version through the "n v12.21.0" command.

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

See all articles