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

青灯夜游
青灯夜游forward
2022-04-24 21:00:452420browse

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:juejin.cn. If there is any infringement, please contact admin@php.cn delete