Fs – Api

const fs = require('fs')
Copy the code

Permission bit mode

Since fs module needs to operate files, operation permissions will be involved, so it is necessary to first know what file permissions are and what permissions are available.

File permission table:

To allocate File owner File Group Other users
Permission to a Read write to perform Read write to perform Read write to perform
Character representation r w x r w x r w x
The figures show that the 4 2 1 4 2 1 4 2 1

File operation permissions are divided into three types: read, write, and execute. Numbers are represented as octal numbers. Octal numbers with permissions are 4, 2, and 1 respectively.

You can open Git in any directory and use the Linux command ls -al to check the permissions of files and folders in the directory

Drwxr-xr-x 1 YONGhu 197121 0 Jun 28 14:41 CoreCopy the code
-rw-r--r-- 1 caozuozhe 197121 293 Jun 23 17:44 index.md
Copy the code

In the directory information above, it is easy to see the username, creation time, and filename, but the most important item is the first (ten-digit character). First on behalf of the file or folder, folder, the d beginning – the beginning of the file, and the back nine on behalf of the current user, the user belongs to group and the other user permissions, per three division, representing read (r), write (w) and execute (x), – on behalf of no current corresponding permissions.

The permission parameter mode applies to Linux and Unix operating systems. The default permission of Windows is readable, writable, and unexecutable. Therefore, the permission bit is expressed in 0o666 and 438 in decimal notation. Note: 0O666 is octal

Identify a flag

In NodeJS, the identifier bits represent operations on files, such as readable, writable, readable and writable, etc. In the following table, the identifier bits of file operations and their corresponding meanings are represented.

symbol meaning
r Reads the file and throws an exception if the file does not exist.
r+ Reads and writes to a file, throwing an exception if the file does not exist.
rs Reading and writing files instructs the operating system to bypass the local file system cache.
w If the file does not exist, it will be created. If the file exists, it will be cleared and written.
wx Write file, open it in exclusive mode.
w+ The file is read and written to. If the file does not exist, the file is created. If the file exists, the file is written to.
wx+ andw+Similarly, exclusive way to open.
a Append write, create file if file does not exist.
ax withaSimilarly, exclusive way to open.
a+ Read and append to, create if not present.
ax+ witha+Similarly, exclusive way to open.
  • R: read
  • W: write
  • S: synchronous
  • + : Adds the reverse operation
  • X: Exclusivity

The difference between r+ and w+ is that r+ will not create a file when the file does not exist, but will throw an exception, but w+ will create the file; If the file exists, r+ will not automatically empty the file, but W + will automatically empty the contents of the existing file.

Fs. readFile Reads data asynchronously

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

Path < string > | < Buffer > | < URL > | < integer > filename or file descriptors options < Object > | < string > encoding < string > | < null > default: Null Flag <string> See support for file system flags. Default value: 'r'. Signal < AbortSignal > allowed to suspend the ongoing read the file callback < XSL: > err < Error > | < AggregateError > data < string > | < Buffer >Copy the code
    fs.readFile('input.txt'.function (err, data) {
       if (err) {
           return console.error(err);
       }
       console.log("Asynchronous read:" + data.toString());
    });

    fs.readFile(path.resolve('data1.txt'), 'utf-8'.(err, data) = > {
        console.log(err) 
        if (!null) {
          console.log(data)
        }
    })
Copy the code

fs.writeFile

fs.writeFile(file, data[, options], callback)

The file < string > | < Buffer > | < URL > | < integer > filename or file descriptor data < string > | < Buffer > | < TypedArray > | < DataView > | < Object > The options < Object > | < string > encoding < string > | < null > default value: 'utf8 mode < integer > default: 0O666 flag <string> See support for file system flags. Default value: 'w'. Signal < AbortSignal > allowed to suspend the ongoing written to the file callback < XSL: > err < Error > | < AggregateError >Copy the code

When file is a file name, data is asynchronously written to the file and replaced if the file already exists. Data can be a string or a buffer. When file is a file descriptor, the behavior is similar to calling fs.write() directly (recommended). If data is a buffer, the encoding option is ignored. If data is an ordinary object, it must have its own (not inherited) toString function property.

    fs.writeFile('data.txt'.'123', {
      mode: 438.flag: 'w+'.encoding: 'utf-8'
    }, (err) = > {
      if(! err) { fs.readFile('data.txt'.'utf-8'.(err, data) = > {
          console.log(data)
        })
      }
    })

    // The method of planting writes
    const controller = new AbortController();
    const { signal } = controller;
    const data = new Uint8Array(Buffer.from('Hello Node.js'));
    writeFile('message.txt', data, { signal }, (err) = > {
      // When the request aborts - call the callback with AbortError
    });
    // When the request should be aborted
    controller.abort();
Copy the code