The introduction of the module

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

Synchronous and asynchronous

All file system operations are synchronous and asynchronous

  • The asynchronous form always takes the completion callback as its last argument. The parameters passed to complete the callback depend on the method, but the first parameter is always reserved for exceptions. If the operation completes successfully, the first argument will be null or undefined. delete
const fs = require('fs');
fs.unlink('/tmp/hello', (err) => {
  if (err) throw err;
  console.log('deleted successfully/TMP /hello');
});
Copy the code
  • Exceptions that occur with synchronized operations are immediately thrown, using a try… Catch processing can also allow bubbling.
const fs = require('fs');
try {
  fs.unlinkSync('/tmp/hello');
  console.log('deleted successfully/TMP /hello'); } catch (err) {// Handle error}Copy the code
  • There is no guarantee of order when using asynchronous methods. Therefore, the following operations are error-prone because the fs.stat() operation may be completed before the fs.rename() operation: fs.stat() checks the file status fs.rename() renames
fs.rename('/tmp/hello'.'/tmp/world', (err) => {
  if (err) throw err;
  console.log('Rename done');
});
fs.stat('/tmp/world', (err, stats) => {
  if(err) throw err; Console. log(' File properties:${JSON.stringify(stats)}`);
});
Copy the code

To sort correctly, move the fs.stat call to the callback of the fs.rename operation:

fs.rename('/tmp/hello'.'/tmp/world', (err) => {
  if (err) throw err;
  fs.stat('/tmp/world', (err, stats) => {
    if(err) throw err; Console. log(' File properties:${JSON.stringify(stats)}`);
  });
});
Copy the code

It is recommended to operate asynchronously, the synchronous version will block the entire process until they complete (stop all connections)

The file path

  • fs.open(path, flag[, mode], callback)
    • path string | Buffer | URL
    • flags string | number
    • mode integer Default: 0o666
    • callback Function
      • err
      • Fd file descriptor
  • Open the file asynchronously. Flags can be:
    • ‘r’ — opens the file in read mode. An exception occurs if the file does not exist.
    • ‘R +’ — Open files in read/write mode. An exception occurs if the file does not exist.
    • ‘RS +’ — open file in synchronous read/write mode. Command the operating system to bypass the local file system cache. This is useful for opening files in NFS mount mode, as it lets you skip potentially old local caches. It has a significant impact on I/O performance, so do not use this flag unless necessary.
'W' - Opens the file in write mode. The file will be created (if it doesn't exist) or truncated (if it does). 'wx' - similar to 'w', but fails if path exists. 'W +' - Opens files in read/write mode. The file will be created (if it doesn't exist) or truncated (if it does). 'wx+' - similar to 'w+', but fails if path exists. 'A' - Opens the file in append mode. If the file does not exist, it will be created. 'ax' - similar to 'a', but fails if path exists. 'A +' - Opens files in read and append mode. If the file does not exist, it will be created. 'AX +' - similar to 'a+', but fails if path exists.Copy the code

Fs.open () sync version — fs.opensync () enters the sync blocking call.

fs.open('/open/some/file.txt'.'r', (err, fd) => {
  if (err) throw err;
  fs.fstat(fd, (err, stat) = > {if(err) throw err; // Use file attributes. // Always close the file descriptor! fs.close(fd, (err) => {if (err) throw err;
    });
  });
});
Copy the code

Fs API

– fs.Dir

async function print(path) {
  const dir = await fs.promises.opendir(path);
  for await (const dirent of dir) {
    console.log(dirent.name);
  }
}
print('./test').catch(console.error);
Copy the code

Traverses the file directory

Most operating systems limit the number of file descriptors that can be opened at any given time, so it is critical to close the descriptor when the operation is complete. Failure to do so will result in a memory leak that will eventually crash the application.

-dir.closesync () -- sync -- dir.path -- Read-only path of this directory -- dir.read(callback) --Copy the code

fs.access(path[, mode], callback)

  • path | |
  • Mode Default: Fs.constants.F_OK.
  • callback
    • Err Tests the permission of a user on a file or directory specified by path.

Constant for file accessibility

constant instructions
F_OK Indicates that the file is visible to the calling process. This is useful for determining whether a file exists, but does not say anything about RWX permissions. If no mode is specified, the default is that value.
R_OK Indicates that the calling process can read the file.
W_OK Indicates that the calling process can write to a file.
X_OK Indicates that the calling process can execute the file. Invalid on Windows (act likefs.constants.F_OK).

Such as:

const file = 'package.json';
// Check whether the file exists in the current directory.
fs.access(file, fs.constants.F_OK, (err) => {
  console.log(`${file} ${err ? 'Nonexistence' : 'there'}`);
});
Copy the code

It is not recommended to use fs.access() to check the accessibility of files before calling apis that manipulate files directly, such as fs.open(), fs.readfile (), or fs.writefile (). Doing so introduces race conditions because other processes may change the state of the file between calls. Instead, open, read, or write the file directly and handle the raised error if the file is not accessible.

fs.existsSync(path)

Return true if the path exists, false otherwise.

if (fs.existsSync('/etc/passwd')) {
  console.log('File already exists');
}
Copy the code
const fs = require('fs');
const assert = require('assert');

console.log(fs.readFileSync('./test/test1.txt'.'utf8'));
// Print: node.js

// Get the file descriptor for the file to truncate.
const fd = fs.openSync('./test/test1.txt'.'r+');

// Truncate the file to the first 4 bytes.
fs.ftruncate(fd, 4, (err) => {
  assert.ifError(err);
  console.log(fs.readFileSync('./test/test1.txt'.'utf8'));
});
// Prints: Node
Copy the code
  1. Fs.mkdir (path[, options], callback) recursive Default: false, indicating whether a parent folder should be created mode is not supported on Windows. Default value: 0O777. Used to set file mode (permissions and sticky bits), but only when creating a file.
// Create the/TMP /a/apple directory, regardless of whether/TMP and/TMP /a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
  if (err) throw err;
});
Copy the code
  1. Fs.opendir (path[, options], callback) opens the directory asynchronously

  2. Fs. read(fd, buffer, offset, length, position, callback) reads data from the file specified by fd. A buffer is a buffer to which data will be written. Offset is the offset at which the buffer starts writing. Length is an integer that specifies the number of bytes to read. The position argument specifies the position from which to start reading in the file. If position is null, the data is read from the current file location and the file location is updated. If position is an integer, the file location remains the same. The callback takes three arguments (err, bytesRead, buffer). If the util.promisify() version of this method is called, the returned Promise returns an Object with the bytesRead and buffer properties.

  3. Fs.readdir (path[, options], callback) reads the contents of the directory callback with two arguments (err, files), where files is an array of file names in the directory (excluding ‘.’ and ‘.. ‘).

  4. Fs. readFile(path[, options], callback) reads the entire contents of the file asynchronously. ,

fs.readFile('./test/test1.txt'.'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
Copy the code

The fs.readfile () function buffers the entire file. To minimize memory costs, stream through fs.createreadStream () whenever possible. 6. fs.rename(oldPath, newPath, callback)

fs.rename('Old file.txt'.'New file.txt', (err) => {
  if (err) throw err;
  console.log('Rename done');
});
Copy the code
  1. Fs.unlink (path, callback) Deletes files or symbolic links.
fs.unlink('path/file.txt', (err) => {
  if (err) throw err;
  console.log('File deleted');
});
Copy the code
  1. Fs.rmdir () deletes the folder

Reference document: NodeJS official website POSIX describes the FS module -fs.open