Three major modules of Node [detailed]

What is the fs file system module

fs是Read and write methods provided by 操纵文件的模块node.js.

Next, let's talk about three things, how 读取文件, 写入文件and one 动态路径的解决问题.

Before using the method of fs, first import fs, the code is very simple and fixed:

const fs  = require('fs');

Then you can execute the read and write methods:

  1. fs.readFile()method, used to read the contents of the specified file
  2. fs.writeFile()method, used to write content to the specified file

Read the contents of the specified file

fs.readFile()The grammatical format of:

fs.readFile(path[,option],callback);
  1. Parameter 1 path: Mandatory parameter, string, indicating the path of the file.
  2. Parameter 2 option: Optional parameter, indicating what encoding format to read the file in.
  3. Parameter 3 callback: Required parameter. After the file is read, the read result is obtained through the callback function.

Take a chestnut:

Read the content of the specified file in utf8 encoding format, and print the values ​​of err and dataStr:

const fs = require('fs');
fs.readFile('./file/1.txt','utf8',function(err,dataStr){
    
    
	console.log(err);  // 打印失败返回的值
	console.log(-------------);
	console.log(dataStr); // 打印成功读取返回的数据
})

Let’s talk about what is the return value when the read is successful errand when the read fails:dataStr

When the read is successful:

  1. err return value: null;
  2. dataStr return value: is the content of the accessed file;

When reading fails:

  1. err return value: It is an error message; the specific error message can be printed out through err.message.
  2. dataStr return value: undefined;

Determine whether the file was read successfully

As we mentioned above, 读取成功时,err的值为null, then we can judge whether the err object is null, so as to know the result of reading the file:

const fs = require('fs');
fs.readFile('./file/1.txt','utf8',function(err,dataStr){
    
    
	if(err){
    
    
		return console.log('文件读取失败'+err.message);
	}
	console.log('文件读取成功'+dataStr);
})

tips:The encoding format in the middle is utf8 by default. If the encoding format is utf8, it can be ignored.

Write content to the specified file

Syntax format of fs.writeFile()

fs.writeFile(file,data[,option],callback);
  1. Parameter 1 file: Required parameter, need to specify a string of file path, indicating the storage path of the file.
  2. Parameter 2 data: Required parameter, indicating the content to be written.
  3. Parameter 3 option: Optional parameter, which indicates the format to write the file content in, and the default value is utf8.
  4. Parameter 4 callback: Required parameter, the callback function after the file is written.

Write content to the specified file

Take a chestnut:

const fs =  require('fs');
fs.writeFile(./file/2.txt,'hello 我就是被写入的内容',function(err){
    
    
	console.log(err);
})

Determine whether the file was written successfully

The method is the same as above: judge whether the err object is null, so as to know the result of writing the file:

const fs =  require('fs');
fs.writeFile(./file/2.txt,'hello 我就是被写入的内容',function(err){
    
    
	if(err){
    
    
		return console.log('文件被写入失败'+err.message);
	}
	console.log('文件被写入成功');
})

The problem of dynamic stitching of paths

When using the fs module to operate files, if the provided operation path is ./a ../relative path starting with or , it is easy to cause path dynamic splicing errors.

Reason: When the code is running, 会以执行 node 命令时所处的目录, dynamically splicing out the full path of the operated file.

Solution: When using the fs module to operate files, 直接提供完整的路径do not provide a relative path starting with ./ or .../, so as to prevent the problem of dynamic path splicing.

Say two ways:

  1. The first one directly provides an absolute path (very poor portability, not conducive to maintenance)
  2. The second one uses __dirname to complete the absolute path
// 第一种
// 移植性非常差、不利于维护

 fs.readFile('C:\\Users\\escook\\Desktop\\code\\file\\1.txt', 'utf8', function(err, dataStr) {
    
    
  if (err) {
    
    
    return console.log('读取文件失败!' + err.message)
  }
  console.log('读取文件成功!' + dataStr)
}) 



//第二种:
// __dirname 表示当前文件所处的目录

fs.readFile(__dirname + '/files/1.txt', 'utf8', function(err, dataStr) {
    
    
  if (err) {
    
    
    return console.log('读取文件失败!' + err.message)
  }
  console.log('读取文件成功!' + dataStr)
})

tips:There are two formal parameters in the function returned by the read method, and only one formal parameter in the return function of the write method;

In fact, using __dirname is not the best way, because there are more convenient modules in node.js. The path method is used to splice the path, get the file name, and the file suffix

Then let's talk about the Path module

path path module

What is the path path module

It provides a series of methods and attributes to meet the needs of users 路径的处理.
举个栗子:

  1. path.join()method for将多个路径片段拼接成一个完整的路径字符串
  2. path.basename()Method, used to parse the file name from the path string

Then if we want to use this method, we need to import it first like fs

const path =  require('path');

So let's talk about how to use these two methods:

path.join()The grammatical format of :

Using path.join()the method , multiple path segments can be spliced ​​into a complete path string;

const path = require('path')
const fs = require('fs')

// 注意:  ../ 会抵消前面的路径
// const pathStr = path.join('/a', '/b/c', '../../', './d', 'e')
// console.log(pathStr)  // \a\b\d\e

// fs.readFile(__dirname + '/files/1.txt')

fs.readFile(path.join(__dirname, './files/1.txt'), 'utf8', function(err, dataStr) {
    
    
  if (err) {
    
    
    return console.log(err.message)
  }
  console.log(dataStr)
})

tips: .../ will offset the previous path.
This method is a perfect match with fs to obtain the file content;

Get the file name in the path :
use path.basename()the method to get the last part of the path, and often use this method to get the file name in the path:

There are two types of file names obtained, the first one contains suffixes, and the second one does not contain suffixes; let’s talk about the first one first: get file names with suffixes:

const path = require('path')

// 定义文件的存放路径
const fpath = '/a/b/c/index.html'
const fullName = path.basename(fpath)
console.log(fullName)   // 此时的输出结果是index.html

The second method: get the file name without suffix:

const path = require('path')
const fpath = '/a/b/c/index.html'
const nameWithoutExt = path.basename(fpath, '.html')   
console.log(nameWithoutExt)            // 此时的输出结果是去掉了.html后缀的 index

tips:The function of path.basename() is to obtain the file name, and its second parameter is used to remove unwanted suffixes.

path also provides us with a method to only get the suffix of the file name: that ispath.extname()

The method of use is very simple, just put in the path of the target file we need to get, and its output is the suffix of this file;

Take a chestnut:

const fpath = '/a/b/c/index.html';   // 定义一个路径字符串
const fext = path.extname(fpath);
console.log(fext);  // 输出结果就是:.html


Keep reviewing, keep being excellent, be practical and do things seriously; pay attention to Sanlian and keep updating~~~

insert image description here

Guess you like

Origin blog.csdn.net/egg_er/article/details/122837996
Recommended