- Node.js v14.16.1 Documentation
- #">File system#
- # 同步形式的例子">Synchronous example# 同步形式的例子
- # 回调函数形式的例子">Callback example# 回调函数形式的例子
- #">Promise example#
- #">Ordering of callback and promise-based operations#
- #">File paths#
- #">File descriptors#
- #">Threadpool usage#
- #">Class:
fs.Dir
# - #">Class:
fs.Dirent
# - #">Class:
fs.FSWatcher
# - #">Class:
fs.StatWatcher
# - #">Class:
fs.ReadStream
# - #">Class:
fs.Stats
#- #">
stats.isBlockDevice()
# - #">
stats.isCharacterDevice()
# - #">
stats.isDirectory()
# - #">
stats.isFIFO()
# - #">
stats.isFile()
# - #">
stats.isSocket()
# - #">
stats.isSymbolicLink()
# - #">
stats.dev
# - #">
stats.ino
# - #">
stats.mode
# - #">
stats.nlink
# - #">
stats.uid
# - #">
stats.gid
# - #">
stats.rdev
# - #">
stats.size
# - #">
stats.blksize
# - #">
stats.blocks
# - #">
stats.atimeMs
# - #">
stats.mtimeMs
# - #">
stats.ctimeMs
# - #">
stats.birthtimeMs
# - #">
stats.atimeNs
# - #">
stats.mtimeNs
# - #">
stats.ctimeNs
# - #">
stats.birthtimeNs
# - #">
stats.atime
# - #">
stats.mtime
# - #">
stats.ctime
# - #">
stats.birthtime
# - #">Stat time values#
- #">
- #">Class:
fs.WriteStream
# - #">
fs.access(path[, mode], callback)
# - #">
fs.accessSync(path[, mode])
# - #">
fs.appendFile(path, data[, options], callback)
# - #">
fs.appendFileSync(path, data[, options])
# - #">
fs.chmod(path, mode, callback)
# - #">
fs.chmodSync(path, mode)
# - #">
fs.chown(path, uid, gid, callback)
# - #">
fs.chownSync(path, uid, gid)
# - #">
fs.close(fd, callback)
# - #">
fs.closeSync(fd)
# - #">
fs.constants
# - #">
fs.copyFile(src, dest[, mode], callback)
# - #">
fs.copyFileSync(src, dest[, mode])
# - #">
fs.createReadStream(path[, options])
# - #">
fs.createWriteStream(path[, options])
# - #">
fs.exists(path, callback)
# - #">
fs.existsSync(path)
# - #">
fs.fchmod(fd, mode, callback)
# - #">
fs.fchmodSync(fd, mode)
# - #">
fs.fchown(fd, uid, gid, callback)
# - #">
fs.fchownSync(fd, uid, gid)
# - #">
fs.fdatasync(fd, callback)
# - #">
fs.fdatasyncSync(fd)
# - #">
fs.fstat(fd[, options], callback)
# - #">
fs.fstatSync(fd[, options])
# - #">
fs.fsync(fd, callback)
# - #">
fs.fsyncSync(fd)
# - #">
fs.ftruncate(fd[, len], callback)
# - #">
fs.ftruncateSync(fd[, len])
# - #">
fs.futimes(fd, atime, mtime, callback)
# - #">
fs.futimesSync(fd, atime, mtime)
# - #">
fs.lchmod(path, mode, callback)
# - #">
fs.lchmodSync(path, mode)
# - #">
fs.lchown(path, uid, gid, callback)
# - #">
fs.lchownSync(path, uid, gid)
# - #">
fs.lutimes(path, atime, mtime, callback)
# - #">
fs.lutimesSync(path, atime, mtime)
# - #">
fs.link(existingPath, newPath, callback)
# - #">
fs.linkSync(existingPath, newPath)
# - #">
fs.lstat(path[, options], callback)
# - #">
fs.lstatSync(path[, options])
# - #">
fs.mkdir(path[, options], callback)
# - #">
fs.mkdirSync(path[, options])
# - #">
fs.mkdtemp(prefix[, options], callback)
# - #">
fs.mkdtempSync(prefix[, options])
# - #">
fs.open(path[, flags[, mode]], callback)
# - #">
fs.opendir(path[, options], callback)
# - #">
fs.opendirSync(path[, options])
# - #">
fs.openSync(path[, flags, mode])
# - #">
fs.read(fd, buffer, offset, length, position, callback)
# - #">
fs.read(fd, [options,] callback)
# - #">
fs.readdir(path[, options], callback)
# - #">
fs.readdirSync(path[, options])
# - #">
fs.readFile(path[, options], callback)
# - #">
fs.readFileSync(path[, options])
# - #">
fs.readlink(path[, options], callback)
# - #">
fs.readlinkSync(path[, options])
# - #">
fs.readSync(fd, buffer, offset, length, position)
# - #">
fs.readSync(fd, buffer, [options])
# - #">
fs.readv(fd, buffers[, position], callback)
# - #">
fs.readvSync(fd, buffers[, position])
# - #">
fs.realpath(path[, options], callback)
# - #">
fs.realpath.native(path[, options], callback)
# - #">
fs.realpathSync(path[, options])
# - #">
fs.realpathSync.native(path[, options])
# - #">
fs.rename(oldPath, newPath, callback)
# - #">
fs.renameSync(oldPath, newPath)
# - #">
fs.rmdir(path[, options], callback)
# - #">
fs.rmdirSync(path[, options])
# - #">
fs.rm(path[, options], callback)
# - #">
fs.rmSync(path[, options])
# - #">
fs.stat(path[, options], callback)
# - #">
fs.statSync(path[, options])
# - #">
fs.symlink(target, path[, type], callback)
# - #">
fs.symlinkSync(target, path[, type])
# - #">
fs.truncate(path[, len], callback)
# - #">
fs.truncateSync(path[, len])
# - #">
fs.unlink(path, callback)
# - #">
fs.unlinkSync(path)
# - #">
fs.unwatchFile(filename[, listener])
# - #">
fs.utimes(path, atime, mtime, callback)
# - #">
fs.utimesSync(path, atime, mtime)
# - #">
fs.watch(filename[, options][, listener])
# - #">
fs.watchFile(filename[, options], listener)
# - #">
fs.write(fd, buffer[, offset[, length[, position]]], callback)
# - #">
fs.write(fd, string[, position[, encoding]], callback)
# - #">
fs.writeFile(file, data[, options], callback)
# - #">
fs.writeFileSync(file, data[, options])
# - #">
fs.writeSync(fd, buffer[, offset[, length[, position]]])
# - #">
fs.writeSync(fd, string[, position[, encoding]])
# - #">
fs.writev(fd, buffers[, position], callback)
# - #">
fs.writevSync(fd, buffers[, position])
# - #">
fs
Promises API#- #">Class:
FileHandle
#- #">
filehandle.appendFile(data, options)
# - #">
filehandle.chmod(mode)
# - #">
filehandle.chown(uid, gid)
# - #">
filehandle.close()
# - #">
filehandle.datasync()
# - #">
filehandle.fd
# - #">
filehandle.read(buffer, offset, length, position)
# - #">
filehandle.read(options)
# - #">
filehandle.readFile(options)
# - #">
filehandle.readv(buffers[, position])
# - #">
filehandle.stat([options])
# - #">
filehandle.sync()
# - #">
filehandle.truncate(len)
# - #">
filehandle.utimes(atime, mtime)
# - #">
filehandle.write(buffer[, offset[, length[, position]]])
# - #">
filehandle.write(string[, position[, encoding]])
# - #">
filehandle.writeFile(data, options)
# - #">
filehandle.writev(buffers[, position])
#
- #">
- #">
fsPromises.access(path[, mode])
# - #">
fsPromises.appendFile(path, data[, options])
# - #">
fsPromises.chmod(path, mode)
# - #">
fsPromises.chown(path, uid, gid)
# - #">
fsPromises.copyFile(src, dest[, mode])
# - #">
fsPromises.lchmod(path, mode)
# - #">
fsPromises.lchown(path, uid, gid)
# - #">
fsPromises.lutimes(path, atime, mtime)
# - #">
fsPromises.link(existingPath, newPath)
# - #">
fsPromises.lstat(path[, options])
# - #">
fsPromises.mkdir(path[, options])
# - #">
fsPromises.mkdtemp(prefix[, options])
# - #">
fsPromises.open(path, flags[, mode])
# - #">
fsPromises.opendir(path[, options])
# - #">
fsPromises.readdir(path[, options])
# - #">
fsPromises.readFile(path[, options])
# - #">
fsPromises.readlink(path[, options])
# - #">
fsPromises.realpath(path[, options])
# - #">
fsPromises.rename(oldPath, newPath)
# - #">
fsPromises.rmdir(path[, options])
# - #">
fsPromises.rm(path[, options])
# - #">
fsPromises.stat(path[, options])
# - #">
fsPromises.symlink(target, path[, type])
# - #">
fsPromises.truncate(path[, len])
# - #">
fsPromises.unlink(path)
# - #">
fsPromises.utimes(path, atime, mtime)
# - #">
fsPromises.writeFile(file, data[, options])
#
- #">Class:
- #">FS constants#
- #">File system flags#
Node.js v14.16.1 Documentation
Table of Contents 目录
File system 文件系统
- Synchronous example 同步例子
- Callback example 回调函数例子
- Promise example Promise例子
- Ordering of callback and promise-based operations 回调函数和Promise形式的文件操作执行顺序排序
- File paths 关于文件路径的说明
- URL object support 文件操作中支持使用URL的形式,所以这里做了一些说明
- File descriptors 文件描述符的说明
- Threadpool usage 线程池的使用,这个不用看,没有讲具体的
- Class:
fs.Dir
fs模块的Dir类 代表读取到的目录类[dir.close()](https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_dir_close)
[dir.close(callback)](https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_dir_close_callback)
[dir.closeSync()](https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_dir_closesync)
[dir.path](https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_dir_path)
dir.read()
dir.read(callback)
dir.readSync()
dir[Symbol.asyncIterator]()
- Class:
fs.Dirent
目录中的条目类 - Class:
fs.FSWatcher
文件系统监视器,这个类感觉有大用处 - Class:
fs.StatWatcher
sata监视器,折现 - Class:
fs.ReadStream
读取流类 - Class:
fs.Stats
sata类,这个类中保存了目录或者文件的很多信息,以及提供了很多方法给开发者使用,用来对文件或者目录进行判断stats.isBlockDevice()
stats.isCharacterDevice()
stats.isDirectory()
stats.isFIFO()
stats.isFile()
stats.isSocket()
stats.isSymbolicLink()
stats.dev
stats.ino
stats.mode
stats.nlink
stats.uid
stats.gid
stats.rdev
stats.size
stats.blksize
stats.blocks
stats.atimeMs
stats.mtimeMs
stats.ctimeMs
stats.birthtimeMs
stats.atimeNs
stats.mtimeNs
stats.ctimeNs
stats.birthtimeNs
stats.atime
stats.mtime
stats.ctime
stats.birthtime
- Stat time values
- Class:
fs.WriteStream
写流类,流的主要功能是对大型文件的读写 [fs.access(path[, mode], callback)](https://nodejs.org/dist/latest-v14.x/docs/api/fs.html#fs_fs_access_path_mode_callback)
fs.accessSync(path[, mode])
fs.appendFile(path, data[, options], callback)
fs.appendFileSync(path, data[, options])
fs.chmod(path, mode, callback)
fs.chmodSync(path, mode)
fs.chown(path, uid, gid, callback)
fs.chownSync(path, uid, gid)
fs.close(fd, callback)
fs.closeSync(fd)
fs.constants
fs.copyFile(src, dest[, mode], callback)
fs.copyFileSync(src, dest[, mode])
fs.createReadStream(path[, options])
fs.createWriteStream(path[, options])
fs.exists(path, callback)
fs.existsSync(path)
fs.fchmod(fd, mode, callback)
fs.fchmodSync(fd, mode)
fs.fchown(fd, uid, gid, callback)
fs.fchownSync(fd, uid, gid)
fs.fdatasync(fd, callback)
fs.fdatasyncSync(fd)
fs.fstat(fd[, options], callback)
fs.fstatSync(fd[, options])
fs.fsync(fd, callback)
fs.fsyncSync(fd)
fs.ftruncate(fd[, len], callback)
fs.ftruncateSync(fd[, len])
fs.futimes(fd, atime, mtime, callback)
fs.futimesSync(fd, atime, mtime)
fs.lchmod(path, mode, callback)
fs.lchmodSync(path, mode)
fs.lchown(path, uid, gid, callback)
fs.lchownSync(path, uid, gid)
fs.lutimes(path, atime, mtime, callback)
fs.lutimesSync(path, atime, mtime)
fs.link(existingPath, newPath, callback)
fs.linkSync(existingPath, newPath)
fs.lstat(path[, options], callback)
fs.lstatSync(path[, options])
fs.mkdir(path[, options], callback)
fs.mkdirSync(path[, options])
fs.mkdtemp(prefix[, options], callback)
fs.mkdtempSync(prefix[, options])
fs.open(path[, flags[, mode]], callback)
fs.opendir(path[, options], callback)
fs.opendirSync(path[, options])
fs.openSync(path[, flags, mode])
fs.read(fd, buffer, offset, length, position, callback)
fs.read(fd, [options,] callback)
fs.readdir(path[, options], callback)
fs.readdirSync(path[, options])
fs.readFile(path[, options], callback)
fs.readFileSync(path[, options])
fs.readlink(path[, options], callback)
fs.readlinkSync(path[, options])
fs.readSync(fd, buffer, offset, length, position)
fs.readSync(fd, buffer, [options])
fs.readv(fd, buffers[, position], callback)
fs.readvSync(fd, buffers[, position])
fs.realpath(path[, options], callback)
fs.realpath.native(path[, options], callback)
fs.realpathSync(path[, options])
fs.realpathSync.native(path[, options])
fs.rename(oldPath, newPath, callback)
fs.renameSync(oldPath, newPath)
fs.rmdir(path[, options], callback)
fs.rmdirSync(path[, options])
fs.rm(path[, options], callback)
fs.rmSync(path[, options])
fs.stat(path[, options], callback)
fs.statSync(path[, options])
fs.symlink(target, path[, type], callback)
fs.symlinkSync(target, path[, type])
fs.truncate(path[, len], callback)
fs.truncateSync(path[, len])
fs.unlink(path, callback)
fs.unlinkSync(path)
fs.unwatchFile(filename[, listener])
fs.utimes(path, atime, mtime, callback)
fs.utimesSync(path, atime, mtime)
fs.watch(filename[, options][, listener])
fs.watchFile(filename[, options], listener)
fs.write(fd, buffer[, offset[, length[, position]]], callback)
fs.write(fd, string[, position[, encoding]], callback)
fs.writeFile(file, data[, options], callback)
fs.writeFileSync(file, data[, options])
fs.writeSync(fd, buffer[, offset[, length[, position]]])
fs.writeSync(fd, string[, position[, encoding]])
fs.writev(fd, buffers[, position], callback)
fs.writevSync(fd, buffers[, position])
fs
Promises API- Class:
FileHandle
filehandle.appendFile(data, options)
filehandle.chmod(mode)
filehandle.chown(uid, gid)
filehandle.close()
filehandle.datasync()
filehandle.fd
filehandle.read(buffer, offset, length, position)
filehandle.read(options)
filehandle.readFile(options)
filehandle.readv(buffers[, position])
filehandle.stat([options])
filehandle.sync()
filehandle.truncate(len)
filehandle.utimes(atime, mtime)
filehandle.write(buffer[, offset[, length[, position]]])
filehandle.write(string[, position[, encoding]])
filehandle.writeFile(data, options)
filehandle.writev(buffers[, position])
fsPromises.access(path[, mode])
fsPromises.appendFile(path, data[, options])
fsPromises.chmod(path, mode)
fsPromises.chown(path, uid, gid)
fsPromises.copyFile(src, dest[, mode])
fsPromises.lchmod(path, mode)
fsPromises.lchown(path, uid, gid)
fsPromises.lutimes(path, atime, mtime)
fsPromises.link(existingPath, newPath)
fsPromises.lstat(path[, options])
fsPromises.mkdir(path[, options])
fsPromises.mkdtemp(prefix[, options])
fsPromises.open(path, flags[, mode])
fsPromises.opendir(path[, options])
fsPromises.readdir(path[, options])
fsPromises.readFile(path[, options])
fsPromises.readlink(path[, options])
fsPromises.realpath(path[, options])
fsPromises.rename(oldPath, newPath)
fsPromises.rmdir(path[, options])
fsPromises.rm(path[, options])
fsPromises.stat(path[, options])
fsPromises.symlink(target, path[, type])
fsPromises.truncate(path[, len])
fsPromises.unlink(path)
fsPromises.utimes(path, atime, mtime)
fsPromises.writeFile(file, data[, options])
- Class:
- FS constants 文件系统模块中涉及到的各种常量都在这里
- File access constants 文件权限常量(这个和Linux系统中的文件权限记忆方式一样)
- File copy constants 文件复制常量
- File open constants 文件打开常量
- File type constants 文件类型常量
- File mode constants 文件模式常量
- File system flags
File system#
Stability: 2 - Stable
Source Code: lib/fs.js
Thefs
module enables interacting with the file system in a way modeled on standard POSIX functions.
fs模块可以以标准的POSIX功能建模的方式与文件系统进行交互。
POSIX:可移植操作系统接口(英语:Portable Operating System Interface,缩写为POSIX),一般指的就是Linux Unix 系统,mac OS也属于。
To use this module:使用这个模块
All file system operations have synchronous, callback, and promise-based forms.const fs = require('fs');
一个文件系统操作有同步、回调函数和基于Promise的三种形式。(async/await也可以支持)Synchronous example# 同步形式的例子
The synchronous form blocks the Node.js event loop and further JavaScript execution until the operation is complete. Exceptions are thrown immediately and can be handled usingtry…catch
, or can be allowed to bubble up.
同步形式阻塞nodejs事件循环并且直到操作完成才进一步去执行后面的JS代码。异常可以立即抛出并且可以使用try catch 处理或者允许往上冒泡。const fs = require('fs');
try {
fs.unlinkSync('/tmp/hello');//注意这里是一个绝对路径
console.log('successfully deleted /tmp/hello');
} catch (err) {
// handle the error
}
Callback example# 回调函数形式的例子
The callback form takes a completion callback function as its last argument and invokes the operation asynchronously. The arguments passed to the completion callback depend on the method, but the first argument is always reserved for an exception. If the operation is completed successfully, then the first argument isnull
orundefined
.const fs = require('fs');
fs.unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
Promise example#
Promise-based operations return aPromise
that is resolved when the asynchronous operation is complete.const fs = require('fs/promises');
(async function(path) {
try {
await fs.unlink(path);
console.log(`successfully deleted ${path}`);
} catch (error) {
console.error('there was an error:', error.message);
}
})('/tmp/hello');
Ordering of callback and promise-based operations#
There is no guaranteed ordering when using either the callback or promise-based methods. For example, the following is prone to error because thefs.stat()
operation might complete before thefs.rename()
operation:
To correctly order the operations, move thefs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
fs.stat()
call into the callback of thefs.rename()
operation:
Or, use the promise-based API:fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
});
const fs = require('fs/promises');
(async function(from, to) {
try {
await fs.rename(from, to);
const stats = await fs.stat(to);
console.log(`stats: ${JSON.stringify(stats)}`);
} catch (error) {
console.error('there was an error:', error.message);
}
})('/tmp/hello', '/tmp/world');
File paths#
Mostfs
operations accept filepaths that may be specified in the form of a string, aBuffer
, or aURL
object using thefile:
protocol.
String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as determined by callingprocess.cwd()
.
Example using an absolute path on POSIX:
Example using a relative path on POSIX (relative toconst fs = require('fs');
fs.open('/open/some/file.txt', 'r', (err, fd) => {
if (err) throw err;
fs.close(fd, (err) => {
if (err) throw err;
});
});
process.cwd()
):
Paths specified using afs.open('file.txt', 'r', (err, fd) => {
if (err) throw err;
fs.close(fd, (err) => {
if (err) throw err;
});
});
Buffer
are useful primarily on certain POSIX operating systems that treat file paths as opaque byte sequences. On such systems, it is possible for a single file path to contain sub-sequences that use multiple character encodings. As with string paths,Buffer
paths may be relative or absolute:
Example using an absolute path on POSIX:
On Windows, Node.js follows the concept of per-drive working directory. This behavior can be observed when using a drive path without a backslash. For examplefs.open(Buffer.from('/open/some/file.txt'), 'r', (err, fd) => {
if (err) throw err;
fs.close(fd, (err) => {
if (err) throw err;
});
});
fs.readdirSync('C:\\')
can potentially return a different result thanfs.readdirSync('C:')
. For more information, seethis MSDN page.URL object support#
Added in: v7.6.0
For mostfs
module functions, thepath
orfilename
argument may be passed as a WHATWGURL
object. OnlyURL
objects using thefile:
protocol are supported.const fs = require('fs');
const fileUrl = new URL('file:///tmp/hello');
fs.readFileSync(fileUrl);
file:
URLs are always absolute paths.
Using WHATWGURL
objects might introduce platform-specific behaviors.
On Windows,file:
URLs with a host name convert to UNC paths, whilefile:
URLs with drive letters convert to local absolute paths.file:
URLs without a host name nor a drive letter will result in a throw:// On Windows :
// - WHATWG file URLs with hostname convert to UNC path
// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
// - WHATWG file URLs with drive letters convert to absolute path
// file:///C:/tmp/hello => C:\tmp\hello
fs.readFileSync(new URL('file:///C:/tmp/hello'));
// - WHATWG file URLs without hostname must have a drive letters
fs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
fs.readFileSync(new URL('file:///c/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
file:
URLs with drive letters must use:
as a separator just after the drive letter. Using another separator will result in a throw.
On all other platforms,file:
URLs with a host name are unsupported and will result in a throw:
A// On other platforms:
// - WHATWG file URLs with hostname are unsupported
// file://hostname/p/a/t/h/file => throw!
fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute
// - WHATWG file URLs convert to absolute path
// file:///tmp/hello => /tmp/hello
fs.readFileSync(new URL('file:///tmp/hello'));
file:
URL having encoded slash characters will result in a throw on all platforms:
On Windows,// On Windows
fs.readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
fs.readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */
// On POSIX
fs.readFileSync(new URL('file:///p/a/t/h/%2F'));
fs.readFileSync(new URL('file:///p/a/t/h/%2f'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
/ characters */
file:
URLs having encoded backslash will result in a throw:// On Windows
fs.readFileSync(new URL('file:///C:/path/%5C'));
fs.readFileSync(new URL('file:///C:/path/%5c'));
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
\ or / characters */
File descriptors#
On POSIX systems, for every process, the kernel maintains a table of currently open files and resources. Each open file is assigned a simple numeric identifier called a file descriptor. At the system-level, all file system operations use these file descriptors to identify and track each specific file. Windows systems use a different but conceptually similar mechanism for tracking resources. To simplify things for users, Node.js abstracts away the specific differences between operating systems and assigns all open files a numeric file descriptor.
Thefs.open()
method is used to allocate a new file descriptor. Once allocated, the file descriptor may be used to read data from, write data to, or request information about the file.
Most operating systems limit the number of file descriptors that may be open at any given time so it is critical to close the descriptor when operations are completed. Failure to do so will result in a memory leak that will eventually cause an application to crash.fs.open('/open/some/file.txt', 'r', (err, fd) => {
if (err) throw err;
fs.fstat(fd, (err, stat) => {
if (err) throw err;
// use stat
// always close the file descriptor!
fs.close(fd, (err) => {
if (err) throw err;
});
});
});
Threadpool usage#
All file system APIs exceptfs.FSWatcher()
and those that are explicitly synchronous use libuv’s threadpool, which can have surprising and negative performance implications for some applications. See theUV_THREADPOOL_SIZE
documentation for more information.Class:
Added in: v12.12.0fs.Dir
#
A class representing a directory stream.
Created byfs.opendir()
,fs.opendirSync()
, orfsPromises.opendir()
.const fs = require('fs');
async function print(path) {
const dir = await fs.promises.opendir(path);
for await (const dirent of dir) {
console.log(dirent.name);
}
}
print('./').catch(console.error);
Added in: v12.12.0dir.close()
#
Asynchronously close the directory’s underlying resource handle. Subsequent reads will result in errors.
A Promise
is returned that will be resolved after the resource has been closed.
dir.close(callback)
#
Added in: v12.12.0
Asynchronously close the directory’s underlying resource handle. Subsequent reads will result in errors.
The callback
will be called after the resource handle has been closed.
dir.closeSync()
#
Added in: v12.12.0
Synchronously close the directory’s underlying resource handle. Subsequent reads will result in errors.
dir.path
#
Added in: v12.12.0
The read-only path of this directory as was provided to fs.opendir()
,fs.opendirSync()
, or fsPromises.opendir()
.
dir.read()
#
Added in: v12.12.0
Asynchronously read the next directory entry via readdir(3)
as anfs.Dirent
.
After the read is completed, a Promise
is returned that will be resolved with an fs.Dirent
, or null
if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as provided by the operating system’s underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
dir.read(callback)
#
Added in: v12.12.0
Asynchronously read the next directory entry via readdir(3)
as anfs.Dirent
.
After the read is completed, the callback
will be called with anfs.Dirent
, or null
if there are no more directory entries to read.
Directory entries returned by this function are in no particular order as provided by the operating system’s underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
dir.readSync()
#
Added in: v12.12.0
Synchronously read the next directory entry via readdir(3)
as anfs.Dirent
.
If there are no more directory entries to read, null
will be returned.
Directory entries returned by this function are in no particular order as provided by the operating system’s underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
dir[Symbol.asyncIterator]()
#
Added in: v12.12.0
Asynchronously iterates over the directory via readdir(3)
until all entries have been read.
Entries returned by the async iterator are always an fs.Dirent
. The null
case from dir.read()
is handled internally.
See fs.Dir
for an example.
Directory entries returned by this iterator are in no particular order as provided by the operating system’s underlying directory mechanisms. Entries added or removed while iterating over the directory might not be included in the iteration results.
Class: fs.Dirent
#
Added in: v10.10.0
A representation of a directory entry, which can be a file or a subdirectory within the directory, as returned by reading from an fs.Dir
. The directory entry is a combination of the file name and file type pairs.
Additionally, when fs.readdir()
or fs.readdirSync()
is called with the withFileTypes
option set to true
, the resulting array is filled withfs.Dirent
objects, rather than strings or Buffers
.
dirent.isBlockDevice()
#
Added in: v10.10.0
Returns true
if the fs.Dirent
object describes a block device.
dirent.isCharacterDevice()
#
Added in: v10.10.0
Returns true
if the fs.Dirent
object describes a character device.
dirent.isDirectory()
#
Added in: v10.10.0
Returns true
if the fs.Dirent
object describes a file system directory.
dirent.isFIFO()
#
Added in: v10.10.0
Returns true
if the fs.Dirent
object describes a first-in-first-out (FIFO) pipe.
dirent.isFile()
#
Added in: v10.10.0
Returns true
if the fs.Dirent
object describes a regular file.
dirent.isSocket()
#
Added in: v10.10.0
Returns true
if the fs.Dirent
object describes a socket.
dirent.isSymbolicLink()
#
Added in: v10.10.0
Returns true
if the fs.Dirent
object describes a symbolic link.
dirent.name
#
Added in: v10.10.0
The file name that this fs.Dirent
object refers to. The type of this value is determined by the options.encoding
passed to fs.readdir()
orfs.readdirSync()
.
Class: fs.FSWatcher
#
Added in: v0.5.8
A successful call to fs.watch()
method will return a new fs.FSWatcher
object.
All fs.FSWatcher
objects emit a 'change'
event whenever a specific watched file is modified.
Event: 'change'
#
Added in: v0.5.8
eventType
The type of change event that has occurred filename
| The filename that changed (if relevant/available)
Emitted when something changes in a watched directory or file. See more details in fs.watch()
.
The filename
argument may not be provided depending on operating system support. If filename
is provided, it will be provided as a Buffer
iffs.watch()
is called with its encoding
option set to 'buffer'
, otherwisefilename
will be a UTF-8 string.
// Example when handled through fs.watch() listener
fs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
if (filename) {
console.log(filename);
// Prints: <Buffer ...>
}
});
Event: 'close'
#
Added in: v10.0.0
Emitted when the watcher stops watching for changes. The closedfs.FSWatcher
object is no longer usable in the event handler.
Event: 'error'
#
Added in: v0.5.8
Emitted when an error occurs while watching the file. The erroredfs.FSWatcher
object is no longer usable in the event handler.
watcher.close()
#
Added in: v0.5.8
Stop watching for changes on the given fs.FSWatcher
. Once stopped, thefs.FSWatcher
object is no longer usable.
watcher.ref()
#
Added in: v14.3.0
When called, requests that the Node.js event loop not exit so long as theFSWatcher
is active. Calling watcher.ref()
multiple times will have no effect.
By default, all FSWatcher
objects are “ref’ed”, making it normally unnecessary to call watcher.ref()
unless watcher.unref()
had been called previously.
watcher.unref()
#
Added in: v14.3.0
When called, the active FSWatcher
object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the FSWatcher
object’s callback is invoked. Calling watcher.unref()
multiple times will have no effect.
Class: fs.StatWatcher
#
Added in: v14.3.0
A successful call to fs.watchFile()
method will return a new fs.StatWatcher
object.
watcher.ref()
#
Added in: v14.3.0
When called, requests that the Node.js event loop not exit so long as theStatWatcher
is active. Calling watcher.ref()
multiple times will have no effect.
By default, all StatWatcher
objects are “ref’ed”, making it normally unnecessary to call watcher.ref()
unless watcher.unref()
had been called previously.
watcher.unref()
#
Added in: v14.3.0
When called, the active StatWatcher
object will not require the Node.js event loop to remain active. If there is no other activity keeping the event loop running, the process may exit before the StatWatcher
object’s callback is invoked. Calling watcher.unref()
multiple times will have no effect.
Class: fs.ReadStream
#
Added in: v0.1.93
Instances of fs.ReadStream
are created and returned using thefs.createReadStream()
function.
Event: 'close'
#
Added in: v0.1.93
Emitted when the fs.ReadStream
‘s underlying file descriptor has been closed.
Event: 'open'
#
Added in: v0.1.93
Emitted when the fs.ReadStream
‘s file descriptor has been opened.
Event: 'ready'
#
Added in: v9.11.0
Emitted when the fs.ReadStream
is ready to be used.
Fires immediately after 'open'
.
readStream.bytesRead
#
Added in: v6.4.0
The number of bytes that have been read so far.
readStream.path
#
Added in: v0.1.93
The path to the file the stream is reading from as specified in the first argument to fs.createReadStream()
. If path
is passed as a string, thenreadStream.path
will be a string. If path
is passed as a Buffer
, thenreadStream.path
will be a Buffer
.
readStream.pending
#
Added in: v11.2.0, v10.16.0
This property is true
if the underlying file has not been opened yet, i.e. before the 'ready'
event is emitted.
Class: fs.Stats
#
History
A fs.Stats
object provides information about a file.
Objects returned from fs.stat()
, fs.lstat()
and fs.fstat()
and their synchronous counterparts are of this type. If bigint
in the options
passed to those methods is true, the numeric values will be bigint
instead of number
, and the object will contain additional nanosecond-precision properties suffixed with Ns
.
Stats {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atimeMs: 1318289051000.1,
mtimeMs: 1318289051000.1,
ctimeMs: 1318289051000.1,
birthtimeMs: 1318289051000.1,
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 }
bigint
version:
BigIntStats {
dev: 2114n,
ino: 48064969n,
mode: 33188n,
nlink: 1n,
uid: 85n,
gid: 100n,
rdev: 0n,
size: 527n,
blksize: 4096n,
blocks: 8n,
atimeMs: 1318289051000n,
mtimeMs: 1318289051000n,
ctimeMs: 1318289051000n,
birthtimeMs: 1318289051000n,
atimeNs: 1318289051000000000n,
mtimeNs: 1318289051000000000n,
ctimeNs: 1318289051000000000n,
birthtimeNs: 1318289051000000000n,
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 }
stats.isBlockDevice()
#
Added in: v0.1.10
Returns true
if the fs.Stats
object describes a block device.
stats.isCharacterDevice()
#
Added in: v0.1.10
Returns true
if the fs.Stats
object describes a character device.
stats.isDirectory()
#
Added in: v0.1.10
Returns true
if the fs.Stats
object describes a file system directory.
If the fs.Stats
object was obtained from fs.lstat()
, this method will always return false
. This is because fs.lstat()
returns information about a symbolic link itself and not the path it resolves to.
stats.isFIFO()
#
Added in: v0.1.10
Returns true
if the fs.Stats
object describes a first-in-first-out (FIFO) pipe.
stats.isFile()
#
Added in: v0.1.10
Returns true
if the fs.Stats
object describes a regular file.
stats.isSocket()
#
Added in: v0.1.10
Returns true
if the fs.Stats
object describes a socket.
stats.isSymbolicLink()
#
Added in: v0.1.10
Returns true
if the fs.Stats
object describes a symbolic link.
This method is only valid when using fs.lstat()
.
stats.dev
#
The numeric identifier of the device containing the file.
stats.ino
#
The file system specific “Inode” number for the file.
stats.mode
#
A bit-field describing the file type and mode.
stats.nlink
#
The number of hard-links that exist for the file.
stats.uid
#
The numeric user identifier of the user that owns the file (POSIX).
stats.gid
#
The numeric group identifier of the group that owns the file (POSIX).
stats.rdev
#
A numeric device identifier if the file represents a device.
stats.size
#
The size of the file in bytes.
stats.blksize
#
The file system block size for i/o operations.
stats.blocks
#
The number of blocks allocated for this file.
stats.atimeMs
#
Added in: v8.1.0
The timestamp indicating the last time this file was accessed expressed in milliseconds since the POSIX Epoch.
stats.mtimeMs
#
Added in: v8.1.0
The timestamp indicating the last time this file was modified expressed in milliseconds since the POSIX Epoch.
stats.ctimeMs
#
Added in: v8.1.0
The timestamp indicating the last time the file status was changed expressed in milliseconds since the POSIX Epoch.
stats.birthtimeMs
#
Added in: v8.1.0
The timestamp indicating the creation time of this file expressed in milliseconds since the POSIX Epoch.
stats.atimeNs
#
Added in: v12.10.0
Only present when bigint: true
is passed into the method that generates the object. The timestamp indicating the last time this file was accessed expressed in nanoseconds since the POSIX Epoch.
stats.mtimeNs
#
Added in: v12.10.0
Only present when bigint: true
is passed into the method that generates the object. The timestamp indicating the last time this file was modified expressed in nanoseconds since the POSIX Epoch.
stats.ctimeNs
#
Added in: v12.10.0
Only present when bigint: true
is passed into the method that generates the object. The timestamp indicating the last time the file status was changed expressed in nanoseconds since the POSIX Epoch.
stats.birthtimeNs
#
Added in: v12.10.0
Only present when bigint: true
is passed into the method that generates the object. The timestamp indicating the creation time of this file expressed in nanoseconds since the POSIX Epoch.
stats.atime
#
Added in: v0.11.13
The timestamp indicating the last time this file was accessed.
stats.mtime
#
Added in: v0.11.13
The timestamp indicating the last time this file was modified.
stats.ctime
#
Added in: v0.11.13
The timestamp indicating the last time the file status was changed.
stats.birthtime
#
Added in: v0.11.13
The timestamp indicating the creation time of this file.
Stat time values#
The atimeMs
, mtimeMs
, ctimeMs
, birthtimeMs
properties are numeric values that hold the corresponding times in milliseconds. Their precision is platform specific. When bigint: true
is passed into the method that generates the object, the properties will be bigints, otherwise they will be numbers.
The atimeNs
, mtimeNs
, ctimeNs
, birthtimeNs
properties arebigints that hold the corresponding times in nanoseconds. They are only present when bigint: true
is passed into the method that generates the object. Their precision is platform specific.atime
, mtime
, ctime
, and birthtime
areDate
object alternate representations of the various times. TheDate
and number values are not connected. Assigning a new number value, or mutating the Date
value, will not be reflected in the corresponding alternate representation.
The times in the stat object have the following semantics:
atime
“Access Time”: Time when file data last accessed. Changed by themknod(2)
,utimes(2)
, andread(2)
system calls.mtime
“Modified Time”: Time when file data last modified. Changed by themknod(2)
,utimes(2)
, andwrite(2)
system calls.ctime
“Change Time”: Time when file status was last changed (inode data modification). Changed by thechmod(2)
,chown(2)
,link(2)
,mknod(2)
,rename(2)
,unlink(2)
,utimes(2)
,read(2)
, andwrite(2)
system calls.birthtime
“Birth Time”: Time of file creation. Set once when the file is created. On filesystems where birthtime is not available, this field may instead hold either thectime
or1970-01-01T00:00Z
(ie, Unix epoch timestamp0
). This value may be greater thanatime
ormtime
in this case. On Darwin and other FreeBSD variants, also set if theatime
is explicitly set to an earlier value than the currentbirthtime
using theutimes(2)
system call.
Prior to Node.js 0.12, the ctime
held the birthtime
on Windows systems. As of 0.12, ctime
is not “creation time”, and on Unix systems, it never was.
Class: fs.WriteStream
#
Added in: v0.1.93
Instances of fs.WriteStream
are created and returned using thefs.createWriteStream()
function.
Event: 'close'
#
Added in: v0.1.93
Emitted when the WriteStream
‘s underlying file descriptor has been closed.
Event: 'open'
#
Added in: v0.1.93
Emitted when the WriteStream
‘s file is opened.
Event: 'ready'
#
Added in: v9.11.0
Emitted when the fs.WriteStream
is ready to be used.
Fires immediately after 'open'
.
writeStream.bytesWritten
#
Added in: v0.4.7
The number of bytes written so far. Does not include data that is still queued for writing.
writeStream.path
#
Added in: v0.1.93
The path to the file the stream is writing to as specified in the first argument to fs.createWriteStream()
. If path
is passed as a string, thenwriteStream.path
will be a string. If path
is passed as a Buffer
, thenwriteStream.path
will be a Buffer
.
writeStream.pending
#
Added in: v11.2.0
This property is true
if the underlying file has not been opened yet, i.e. before the 'ready'
event is emitted.
fs.access(path[, mode], callback)
#
History
Tests a user’s permissions for the file or directory specified by path
. The mode
argument is an optional integer that specifies the accessibility checks to be performed. Check File access constants for possible values of mode
. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. fs.constants.W_OK | fs.constants.R_OK
).
The final argument, callback
, is a callback function that is invoked with a possible error argument. If any of the accessibility checks fail, the error argument will be an Error
object. The following examples check ifpackage.json
exists, and if it is readable or writable.
const file = 'package.json';
// Check if the file exists in the current directory.
fs.access(file, fs.constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
// Check if the file is readable.
fs.access(file, fs.constants.R_OK, (err) => {
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});
// Check if the file is writable.
fs.access(file, fs.constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});
// Check if the file exists in the current directory, and if it is writable.
fs.access(file, fs.constants.F_OK | fs.constants.W_OK, (err) => {
if (err) {
console.error(
`${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
} else {
console.log(`${file} exists, and it is writable`);
}
});
Do not use fs.access()
to check for the accessibility of a file before callingfs.open()
, fs.readFile()
or fs.writeFile()
. Doing so introduces a race condition, since other processes may change the file’s state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.
write (NOT RECOMMENDED)
fs.access('myfile', (err) => {
if (!err) {
console.error('myfile already exists');
return;
}
fs.open('myfile', 'wx', (err, fd) => {
if (err) throw err;
writeMyData(fd);
});
});
write (RECOMMENDED)
fs.open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
writeMyData(fd);
});
read (NOT RECOMMENDED)
fs.access('myfile', (err) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
fs.open('myfile', 'r', (err, fd) => {
if (err) throw err;
readMyData(fd);
});
});
read (RECOMMENDED)
fs.open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
readMyData(fd);
});
The “not recommended” examples above check for accessibility and then use the file; the “recommended” examples are better because they use the file directly and handle the error, if any.
In general, check for the accessibility of a file only if the file will not be used directly, for example when its accessibility is a signal from another process.
On Windows, access-control policies (ACLs) on a directory may limit access to a file or directory. The fs.access()
function, however, does not check the ACL and therefore may report that a path is accessible even if the ACL restricts the user from reading or writing to it.
fs.accessSync(path[, mode])
#
History
Synchronously tests a user’s permissions for the file or directory specified by path
. The mode
argument is an optional integer that specifies the accessibility checks to be performed. Check File access constants for possible values of mode
. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. fs.constants.W_OK | fs.constants.R_OK
).
If any of the accessibility checks fail, an Error
will be thrown. Otherwise, the method will return undefined
.
try {
fs.accessSync('etc/passwd', fs.constants.R_OK | fs.constants.W_OK);
console.log('can read/write');
} catch (err) {
console.error('no access!');
}
fs.appendFile(path, data[, options], callback)
#
History