Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Node .js file system


May 10, 2021 Node.js



File system

Node .js documentation provides a detailed .js of Node's file system.

稳定性: 3 - 稳定

The node .js file system module is a collection that encapsulates standard POSIX file I/O operations. Use require('fs') where all methods are synchronized and asynchronous.

The last argument of an asynchronous method is a callback function, and the parameters of this callback depend on the method, although the first argument is generally an exception. If the operation is successful, the first argument null undefined

When using a synchronization operation, any exception is thrown immediately, and the exception can be handled with try/catch to make the program work properly.

Here is an example of an asynchronous operation:

var fs = require('fs');

fs.unlink('/tmp/hello', function (err) {
  if (err) throw err;
  console.log('successfully deleted /tmp/hello');
});

Here's an example of a synchronization operation:

var fs = require('fs');

fs.unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');

Asynchronous methods do not guarantee the order of operations, so the following example is prone to errors:

fs.rename('/tmp/hello', '/tmp/world', function (err) {
  if (err) throw err;
  console.log('renamed complete');
});
fs.stat('/tmp/world', function (err, stats) {
  if (err) throw err;
  console.log('stats: ' + JSON.stringify(stats));
});

The reason for the error in this example is probably that the fs.stat and the correct method is as follows:

fs.rename('/tmp/hello', '/tmp/world', function (err) {
  if (err) throw err;
  fs.stat('/tmp/world', function (err, stats) {
    if (err) throw err;
    console.log('stats: ' + JSON.stringify(stats));
  });
});

Asynchronous methods are highly recommended in busy processes. The synchronization method blocks the entire process until the method is complete.

A relative path may be used, which is process.cwd()

Most fs functions ignore callback parameters and, if ignored, throw exceptions with the default function. If you want stack information for the original call point, you need to set the environment NODE_DEBUG:

$ cat script.js
function bad() {
  require('fs').readFile('/');
}
bad();

$ env NODE_DEBUG=fs node script.js
fs.js:66
        throw err;
              ^
Error: EISDIR, read
    at rethrow (fs.js:61:21)
    at maybeCallback (fs.js:79:42)
    at Object.fs.readFile (fs.js:153:18)
    at bad (/path/to/script.js:2:17)
    at Object.<anonymous> (/path/to/script.js:5:1)
    <etc.>

fs.rename(oldPath, newPath, callback)

Asynchronous function reame (2). T he callback function has only one argument: a possible exception.

fs.renameSync(oldPath, newPath)

The synchronization function reame (2). Return undefined

fs.ftruncate(fd, len, callback)

The asynchronous function ftruncate (2). The callback function has only one argument: a possible exception.

fs.ftruncateSync(fd, len)

The synchronization function ftruncate (2). Return undefined

fs.truncate(path, len, callback)

The asynchronous function truncate (2). T he callback function has only one argument: a possible exception. The file descriptor can also be used as the first argument, and in fs.ftruncate()

fs.truncateSync(path, len)

The synchronization function truncate (2). Return undefined

fs.chown(path, uid, gid, callback)

The asynchronous function chown (2). The callback function has only one argument: a possible exception.

fs.chownSync(path, uid, gid)

The synchronization function chown (2). Return undefined

fs.fchown(fd, uid, gid, callback)

Asynchronous function fchown (2). The callback function has only one argument: a possible exception.

fs.fchownSync(fd, uid, gid)

The synchronization function fchown (2). Return undefined

fs.lchown(path, uid, gid, callback)

Asynchronous function lchown (2). The callback function has only one argument: a possible exception.

fs.lchownSync(path, uid, gid)

The synchronization function lchown (2). Return undefined

fs.chmod(path, mode, callback)

Asynchronous function chmod (2). The callback function has only one argument: a possible exception.

fs.chmodSync(path, mode)

The synchronization function chmod (2). Return undefined

fs.fchmod(fd, mode, callback)

Asynchronous function fchmod (2). The callback function has only one argument: a possible exception.

fs.fchmodSync(fd, mode)

The synchronization function fchmod (2). Return undefined

fs.lchmod(path, mode, callback)

Asynchronous function lchmod (2). The callback function has only one argument: a possible exception.

Available only on Mac OS X.

fs.lchmodSync(path, mode)

The synchronization function lchmod (2). Return undefined

fs.stat(path, callback)

The asynchronous function stat (2). T he callback function has two parameters: (err, stats), stats is fs.Stats object. F or more information, please refer to fs. S tats。

fs.lstat(path, callback)

The asynchronous function lstat (2). T he callback function has two parameters: (err, stats), stats is fs.Stats object. lstat() stat() difference being that if path is path link, it reads the link itself, not the file to which it is linked.

fs.fstat(fd, callback)

The asynchronous function fstat (2). T he callback function has two parameters: (err, stats), where stats is an fs.Stats object.

fs.statSync(path)

The synchronization function stat (2). R eturn fs.Stats instance.

fs.lstatSync(path)

The synchronization function lstat (2). R eturn fs.Stats instance.

fs.fstatSync(fd)

The synchronization function fstat (2). R eturn fs.Stats instance.

fs.link(srcpath, dstpath, callback)

Asynchronous function link (2). The callback function has only one argument: a possible exception.

fs.linkSync(srcpath, dstpath)

Sync function link (2). Return undefined

fs.symlink(srcpath, dstpath[, type], callback)

Asynchronous function symlink (2). The callback function has only one argument: a possible exception.

type may 'dir' 'file' 'junction' (the default 'file' and is only valid in Windows (other systems are not considered). N ote that Windows Junction requires the destination address to be absolute. When 'junction' the destination automatically converted to an absolute path.

fs.symlinkSync(srcpath, dstpath[, type])

Sync function symlink (2). Return undefined

fs.readlink(path, callback)

Asynchronous function readlink (2). The callback function has 2 (err, linkString) .

fs.readlinkSync(path)

The synchronization function readlink (2). Returns the string value of the symbolic link.

fs.realpath(path[, cache], callback)

The asynchronous function realpath (2). T he callback function has 2 (err,resolvedPath) You process.cwd to solve the relative path problem.

For example:

var cache = {'/etc':'/private/etc'};
fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
  if (err) throw err;
  console.log(resolvedPath);
});

fs.realpathSync(path[, cache])

The synchronization function realpath (2). Returns the resolved path.

fs.unlink(path, callback)

Asynchronous function unlink (2). The callback function has only one argument: a possible exception.

fs.unlinkSync(path)

The synchronization function unlink (2). Return undefined

fs.rmdir(path, callback)

Asynchronous function rmdir (2). The callback function has only one argument: a possible exception.

fs.rmdirSync(path)

The synchronization function rmdir (2). Return undefined

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

Asynchronous function mkdir (2). T he callback function has only one argument: a possible exception. mode defaults 0777 .

fs.mkdirSync(path[, mode])

The synchronization function mkdir (2). Return undefined

fs.readdir(path, callback)

The asynchronous function readdir (3). R ead the contents of the folder. T he callback has 2 (err, files) are in the folder except the name '.' a nd '.'. All file names other than .

fs.readdirSync(path)

The synchronization function readdir (3). R eturns in addition to the '.' a nd '..' All the files except.

fs.close(fd, callback)

Asynchronous function close (2). The callback function has only one argument: a possible exception.

fs.closeSync(fd)

The synchronization function close (2). Return undefined

fs.open(path, flags[, mode], callback)

Asynchronous function file open. S ee open (2). flags are:

  • 'r' - Opens in read-only mode and throws an exception if the file does not exist.

  • 'r+' - opens in read-write mode and throws an exception if the file does not exist.

  • 'rs' - Synchronized, open in read-only mode; T his feature is primarily used to open NFS-mounted files because it allows you to skip potentially outdated local caches. Do not use this flag bit if you care about I/O performance.

    This is not the fs.open() a synchronous blocking request, and if you fs.openSync()

  • 'rs+' - Open the file as read and write in sync mode. See 'rs' .

  • 'w' - Opens in write-only mode. The file is either created (if the file does not exist) or overwritten (if present).

  • 'wx' - similar 'w' if the file storage operation fails

  • 'w+' - Opens as readable and writeable. T he file is created (if the file does not exist) or overwritten (if present)

  • 'wx+' - similar to 'w+' if the file storage operation fails.

  • 'a' - Opens in an additional form. If the file does not exist, create one.

  • 'ax' - similar 'a' if the file storage operation fails.

  • 'a+' the file as read-only and attached. If the file does not exist, it is established

  • 'ax+' and 'a+' similar if the file storage operation fails.

If the file exists, mode sets the file mode (permission and sticky bits). The default 0666 readable and written.

The callback has 2 (err, fd) .

Excluding the 'x' (the O_EXCL for open(2)) guarantees path is newly created. O_EXCL I n POSIX systems, files are considered to exist even if they do not exist. Exclusion tags do not determine whether they are valid in the network file system.

In Linux systems, files opened in append mode cannot be written in a specified location. The core of the system ignores the location parameters and writes the data to the end of the file each time.

fs.openSync(path, flags[, mode])

fs.open() Returns a file descriptor in integer form.

fs.utimes(path, atime, mtime, callback)

Change the timestamp of the specified path file.

fs.utimesSync(path, atime, mtime)

fs.utimes() Return undefined

fs.futimes(fd, atime, mtime, callback)

Change the timestamp that the incoming file descriptor points to the file.

fs.futimesSync(fd, atime, mtime)

fs.futimes() Return undefined

fs.fsync(fd, callback)

Asynchronous function fsync (2). The callback function has only one argument: a possible exception.

fs.fsyncSync(fd)

Synchronize fsync (2). Return undefined

fs.write(fd, buffer, offset, length[, position], callback)

Write buffer to the file specified by fd

The offset length determine which part of the cache is written.

The argument position the location of the file to be written to. I f typeof position !== 'number' be written at the current location. See pwrite (2).

The callback function has three (err, written, buffer) written of the buffer are used to write.

Note that if fs.write has not been executed, fs.write which is not safe. Therefore, fs.createWriteStream

In Linux systems, files opened in append mode cannot be written in a specified location. The core of the system ignores the location parameters and writes the data to the end of the file each time.

fs.write(fd, data[, position[, encoding]], callback)

Write buffer to the file specified by fd If data not a buffer, it is cast to a string.

The argument position the location of the file to be written to. I f typeof position !== 'number' be written at the current location. See pwrite (2).

Argument encoding How strings are encoded.

The callback function has three (err, written, buffer) written of the buffer are used to write. N ote that the bytes written are different from the string characters. See Buffer.byteLength.

Between writing buffer the entire string must be written and not intercepted. This is because the displacement of the returned byte is different from the displacement of the string.

Note that if fs.write has not been executed, fs.write which is not safe. Therefore, fs.createWriteStream

In Linux systems, files opened in append mode cannot be written in a specified location. The core of the system ignores the location parameters and writes the data to the end of the file each time.

fs.writeSync(fd, buffer, offset, length[, position])

fs.writeSync(fd, data[, position[, encoding]])

fs.write() Returns the number of bytes to write.

fs.read(fd, buffer, offset, length, position, callback)

Read fd specified file.

buffer a buffer and the data will be written here.

offset write offset

length the file that length needs to read

position reads the starting position of the position null it will be read from the current location.

The callback function has 3 (err, bytesRead, buffer) .

fs.readSync(fd, buffer, offset, length, position)

fs.read Returns bytesRead

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

  • filename {String}
  • options {Object}
    • encoding {String | Null's default is null
    • flag (String) default s 'r'
  • callback {Function}

Read the contents of the entire file asynchronously. For example:

fs.readFile('/etc/passwd', function (err, data) {
  if (err) throw err;
  console.log(data);
});

The callback function has 2 (err, data) are the data of the file. If the parameter encoding specified, the native buffer is returned

fs.readFileSync(filename[, options])

fs.readFile Returns the contents of the entire file.

If the parameter encoding specified, a buffer is returned.

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

  • filename {String}
  • data {String | Buffer}
  • options {Object}
    • encoding {String | Null's default is 'utf8'
    • mode {Number} Default = 438 (aka 0666 in Octal)
    • flag {String} Default = 'w'
  • callback {Function}

Write the file asynchronously and replace it if it already exists. data can be a cache or a string.

If the data is buffer, the parameter encoding The default is 'utf8'

Columns such as:

fs.writeFile('message.txt', 'Hello Node', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
});

fs.writeFileSync(filename, data[, options])

fs.writeFile Return undefined

fs.appendFile(filename, data[, options], callback)

  • filename {String}
  • data {String | Buffer}
  • options {Object}
    • encoding {String | Null's default is 'utf8'
    • mode (Number) Default s 438 (aka 0666 in Octal)
    • flag are the default of 'a'
  • callback {Function}

Add data to the file asynchronously and create one if the file does not exist. data can be a cache or a string.

For example:

fs.appendFile('message.txt', 'data to append', function (err) {
  if (err) throw err;
  console.log('The "data to append" was appended to file!');
});

fs.appendFileSync(filename, data[, options])

fs.appendFile Return undefined

fs.watchFile(filename[, options], listener)

稳定性: 2 - 不稳定。  尽可能的用 fs.watch 来替换。

Monitor filename files. Listener is called whenever a file is listener

The second argument is optional. I f so, it must contain objects with two persistent interval and interval). persistent whether the process continues to run when the file is monitored. interval specifies the interval, in milliseconds, between query files. The default value is .persistent: true, interval: 5007.

Listener has two parameters, the first for the current state of the file and the second for the previous state of the file:

fs.watchFile('message.text', function (curr, prev) {
  console.log('the current mtime is: ' + curr.mtime);
  console.log('the previous mtime was: ' + prev.mtime);
});

The file state object type in listener is fs. Stat。

If you want to be notified when you modify a file, rather than when you access curr.mtime prev.mtime

fs.unwatchFile(filename[, listener])

稳定性: 2 - 不稳定. 尽可能的用 fs.watch 来替换。

Stop monitoring filename files. I f a listener it will only be listener Otherwise, remove all listener and stop monitoring filename

Calling fs.unwatchFile() monitoring an unsnoted file, does not trigger an error, but a no-op occurs.

fs.watch(filename[, options][, listener])

稳定性: 2 - 不稳定.

Observe changes to files or folders specified by filename T he return object is fs. FSWatcher

The second argument is optional. I f so, it must be an object that contains two persistent recursive persistent whether the process continues to run when the file is monitored. recursive whether to monitor all sub-folders or current folders, a parameter that is valid only if the monitoring object is a folder and only in supported systems (see notes below).

The default { persistent: true, recursive: false } .

The callback function has 2 (event, filename) event is rename or change filename file name that triggered the event.

Precautions

fs.watch APIs are not 100% cross-platform compatible and may not be available in some cases.

recursive parameter is only available on OS X. FSEvents monitoring of this type of file, so it is unlikely that new platforms will be added in the future.

Availability

These features rely on the underlying system to provide notification of file system changes.

  • Linux system, inotify .
  • BSD system, kqueue .
  • OS X, files use kqueue folders use FSEvents .
  • SunOS systems, including Solaris and SmartOS, use event ports .
  • Windows system, dependent with ReadDirectoryChangesW .

If the underlying system function is fs.watch does not work. F or example, monitoring network file systems (NFS, SMBs, etc.) is often not useful. Y ou can still query fs.watchFile but it's slow and unreliable.

The file name parameter

Callback functions provide file name parameters that are not available on every platform (not for Linux and Windows). E ven on available platforms, there is no guarantee that they will be available. So don't assume that the filename callback function is valid, add some empty logical judgment to your code.

fs.watch('somedir', function (event, filename) {
  console.log('event is: ' + event);
  if (filename) {
    console.log('filename provided: ' + filename);
  } else {
    console.log('filename not provided');
  }
});

fs.exists(path, callback)

To determine the existence of a file, the callback function argument is the bool value. For example:

fs.exists('/etc/passwd', function (exists) {
  util.debug(exists ? "it's there" : "no passwd!");
});

fs.exists() an older version of the function, so don't use it in code.

In addition, to determine if there is a vulnerability before opening the file, another process may have removed the file between the fs.exists() and fs.open() calls. It is best fs.open() to determine if there is an error based on the callback function.

fs.exists() removed in the future.

fs.existsSync(path)

fs.exists() If the file exists to true otherwise false is false

fs.existsSync() in the future.

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

Test the user rights of path that the parameter path points to. T he optional parameter mode an integer, which represents the permissions that need to be checked. A ll values are listed below. mode can be a single value, or multiple permission checks can be performed by or through a mask operation.

  • fs.F_OK - The file is visible to the process and can be used to check for the existence of the file. T he mode for the argument mode.
  • fs.R_OK Whether the file is readable to the process.
  • fs.W_OK Whether the file is writeable to the process.
  • fs.X_OK - Whether the file is executable for the process. ( Windows system is not available, the execution effect is equivalent fs.F_OK

The third argument is the callback function. I f the check fails, the argument to the callback function is an error in the response. The following example checks whether /etc/passwd can be read and written by the current process.

fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function(err) {
  util.debug(err ? 'no access!' : 'can read/write');
});

fs.accessSync(path[, mode])

fs.access I f an error is thrown, nothing is done.

Class: fs. Stats

fs.stat() fs.lstat() and fs.fstat() as the returned objects of the synchronized version.

  • stats.isFile()
  • stats.isDirectory()
  • stats.isBlockDevice()
  • stats.isCharacterDevice()
  • stats.isSymbolicLink() (only valid with fs.lstat() )
  • stats.isFIFO()
  • stats.isSocket()

Using util.inspect(stats) a string similar to the following:

{ dev: 2114,
  ino: 48064969,
  mode: 33188,
  nlink: 1,
  uid: 85,
  gid: 100,
  rdev: 0,
  size: 527,
  blksize: 4096,
  blocks: 8,
  atime: Mon, 10 Oct 2011 23:24:11 GMT,
  mtime: Mon, 10 Oct 2011 23:24:11 GMT,
  ctime: Mon, 10 Oct 2011 23:24:11 GMT,
  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }

atime mtime birthtime ctime are ctime of Date and need to be compared in the appropriate way. used to get the timestamp (milliseconds, starting at 1 January 1970 00:00:00 UTC), which basically meets any comparison criteria. T here are other ways to display additional information. See MDN JavaScript Reference for more

Stat Time Values

State objects have the following semantics:

  • atime Time - The last time the file was accessed. mknod(2) utimes(2) read(2) can be changed.
  • mtime time - the last time the file was modified. mknod(2) utimes(2) write(2) can be changed.
  • ctime change time - the last modification time of the file state (inode). chmod(2) chown(2) link(2) mknod(2) rename(2) unlink(2) utimes(2) read(2) write(2) can be changed.
  • birthtime "Birth Time" - File creation time, file creation time. I n some file systems that do not provide file lifetime, this field is populated with ctime or 1970-01-01T00:00Z (ie, unix epoch timestamp 0). In Darwin and other FreeBSD system variants, atime is also explicitly set to a time value earlier than its current firsttime, a process that uses utimes(2) system calls.

Prior to the version of Node v0.12, there was a time value for ctime in Windows systems. Note that in v.0.12, ctime is no longer "creation time", and in Unix systems, he has not.

fs.createReadStream(path[, options])

Returns a readable stream object Readable Stream

options default is as follows:

{ flags: 'r',
  encoding: null,
  fd: null,
  mode: 0666,
  autoClose: true
}

The options the start and end to read a specific range of contents of the file, not the entire file. start and end both in the file range and start at 0, encoding 'utf8' 'ascii' 'base64'

If you fd value, ReadStream ignores path parameter and uses the file description so that no open event open

If autoClose false, files won't close even if an error occurs, and you'll be responsible for closing them to avoid file descriptors being leaked. I f autoClose true (the default), the file descriptor is end off when you encounter error or end. error

For example, from a 100-byte file, read at least 10 bytes:

fs.createReadStream('sample.txt', {start: 90, end: 99});

Class: fs. ReadStream

ReadStream is Readable Stream.

Event: 'open'

  • fd used by fd .

Triggered when you create ReadStream for a file.

fs.createWriteStream(path[, options])

Return a new write object Writable Stream

options is an object, the default:

{ flags: 'w',
  encoding: null,
  fd: null,
  mode: 0666 }

Options can also include a start option to write data to the start of the specified file. Modifying without replacing the file requires the flags pattern to be specified as r-plus rather than a silent w.

Similar to ReadStream fd empty, WriteStream path and instead uses the file description so that no open event is open

Class: fs. WriteStream

WriteStream is Writable Stream.

Event: 'open'

  • fd used by fd

Triggered when the WhiteStream file is opened.

file.bytesWritten

The number of bytes currently written, excluding data waiting to be written.

Class: fs. FSWatcher

fs.watch() is this class.

watcher.close()

Stop fs.FSWatcher object.

Event: 'change'

  • event type of event that has changed
  • filename (String) Changed File Name (if relevant/available)

When a listening file or folder changes, see fs.watch.

Event: 'error'

  • error {Error object}

Triggered when an error occurs.

Related articles

JavaScript errors - throw, try, and catch