fs module, read

  1. fs filesystem module

    The fs module is a module for manipulating files and has a series of methods and properties. Such as fs.readFile() fs.writeFile().


  2. Import fs module

    Before using the fs module to manipulate files, you need to import it:

    1
    const fs = require('fs')

    The require() method takes a string to write to a module. The fs module is available in the node installation package.


  3. **Read the contents of the specified file: fs.readFile() **

    1
    fs.readFile(path[, options], callback)

    Parameter 1: Required parameter, string, indicating the path of the file.

    Parameter 2: An optional parameter, indicating what encoding format to read the file in. The default is utf8.

    Parameter 3: Required parameter. After the file is read, the read result will be obtained through the callback function.


    For example: in utf8 encoding format, read the contents of the specified file, and print the values of err and dataStr:

    1
    2
    3
    4
    5
    6
    const fs = require('fs')
    fs.readFile('./files/11.txt', 'utf8', function(err, dataStr){
    console.log(err)
    console.log('-----')
    console.log(dataStr)
    })

    If the read was successful, the err value is null. If the read fails, dataStr is undefined and err is an error object.


  4. Determine whether the file is read successfully

    It can be determined whether the err object is null. if(err === null){} or if (err){return...} . The two spellings are logically opposite.

    Note that when an error is thrown, err is the error object, and err.message is the error message based on the err code.


Share