fs module, read

  1. **Write content to the specified file: fs.writeFile() **

    1
    fs.writeFile(path, data[, options], callback)

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

    Parameter 2: Required parameter, indicating the content to be written.

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

    Parameter 4: Required parameter. After the file is read, the read result will be obtained through the callback function. Called whether the write succeeds or fails.


    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
    const fs = require('fs')
    fs.writeFile('./files/12.txt', 'added information', 'utf8', function(err){
    console.log(err)
    })

    If the writing is successful, the err value is null (so do not write err.message directly here, because the callback function will be executed regardless of success or failure, and there is no message on success).

    If the read fails, the err value is an error object.


  2. Determine whether the file is written successfully

    According to whether err can be converted to true: if(err){return...}

    If err can be turned to true, it means that the err object is not null and the writing fails.


  3. fs.writeFile() writing mechanism

    fs.writeFile() writes to replace the file contents, not append to the original contents.

    When no file is specified, a new file is created and then the contents are written. But if no directory is specified, an error will be reported.


  4. Append content to the specified file appendFile()

    1
    fs.appendFile(filepath, data[, options], callback_function);

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

    Parameter 2: Required parameter, indicating the content to be written.

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

    Parameter 4: Required parameter. After the file is read, the read result will be obtained through the callback function. Called whether the write succeeds or fails.

    Basically the same as fs.writeFile(). Appends do not automatically wrap or whitespace.


  5. Append content to the specified file synchronously appendFileSync()

    1
    fs.appendFileSync(filepath, data[, options]);

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

    Parameter 2: Required parameter, indicating the content to be written.

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


Share