fs file system module

fs file system module

The fs module is officially provided by Node.js and is used to manipulate files. If you want to use the fs module to manipulate files in the js code, you need to use the require function to import the fs module first. Import method:const fs = require('fs')

Methods and attributes provided by the fs module

1. The fs.readFile() method is used to read the contents of the specified file

Grammatical format fs.readFile(path[,options],callback)The content enclosed in square brackets is an optional parameter, and the unenclosed content is a required parameter

  • path: required parameter, string, used to indicate the path of the file
  • options: optional parameter, indicating what encoding format to use to read the file
  • callback: a required parameter, after the file is read, the read result is obtained through the callback function

Specific use
insert image description here

Determine whether the file was read successfully

insert image description here

2.fs.writeFile() method, used to write content to the specified file

grammatical formatfs.writeFile(file,data[,options],callback)

  • file: Required parameter, you need to specify a string of file path, indicating the storage path of the file
  • data: Required parameter, indicating the content to be written
  • options: optional parameter, indicating what format to write the file content in, the default value is utf8
  • callback: Required parameter, the callback function after the file is written

Specific use
insert image description here

Determine whether the write is successful

insert image description here

Note : When using the fs.writeFile() method to write content to the specified file, if the file does not exist, a new file will be automatically created and the content will be written to the created new file. However, when the specified file already exists , the content in the original file will be overwritten automatically, and only the newly written content will be in the file

Path dynamic splicing

When using the fs module to operate files, if the provided operation path is a relative path starting with . or .../, when the code is running, it will dynamically splice out the complete operation file with the directory where the node command is executed path , it is easy to have the problem of path dynamic splicing error.
solve

  1. When using the fs module to operate files, provide the complete path directly, but using this method, the code portability is very poor, which is not conducive to later maintenance
  2. _ _dirname indicates the directory where the current file is located. In the file path, _ _dirname and relative path can be used for splicing (recommended)

Guess you like

Origin blog.csdn.net/qq_62755767/article/details/127210452