Exports
[<Class>]
type Exports =
static member access: Access
static member appendFile: AppendFile
static member chmod: Chmod
static member chown: Chown
static member close: Close
static member constants: Constants2
static member copyFile: CopyFile
static member exists: Exists
static member fchmod: Fchmod
static member fchown: Fchown
static member fdatasync: Fdatasync
static member fstat: Fstat
static member fsync: Fsync
static member ftruncate: Ftruncate
static member futimes: Futimes
static member lchmod: Lchmod
static member lchown: Lchown
static member link: Link
static member lstat: Lstat
static member lstatSync: StatSyncFn
static member lutimes: Lutimes
static member mkdir: Mkdir
static member mkdtemp: Mkdtemp
static member open: Open
static member opendir: Opendir
static member promises: Promises
static member read: Read
static member readFile: ReadFile
static member readdir: Readdir
static member readlink: Readlink
static member readv: Readv
static member realpath: Realpath
static member realpathSync: RealpathSync
static member rename: Rename
static member rm: Rm
static member rmdir: Rmdir
static member stat: Stat
static member statSync: StatSyncFn
static member statfs: Statfs
static member symlink: Symlink
static member truncate: Truncate
static member unlink: Unlink
static member utimes: Utimes
static member write: Write
static member writeFile: WriteFile
static member writev: Writev2
static member Dir () : Dir
static member Dirent<'Name> () : Dirent<'Name>
static member ReadStream (?opts: ReadableOptions<Readable>) : ReadStream
static member StatsFs () : StatsFs
static member WriteStream (?opts: WritableOptions<Writable>) : WriteStream
static member accessSync (path: PathLike, ?mode: float) : unit
static member appendFileSync (path: PathOrFileDescriptor, data: U2<string,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>>, ?options: U2<string,WriteFileOptions2>) : unit
static member chmodSync (path: PathLike, mode: Mode) : unit
static member chownSync (path: PathLike, uid: float, gid: float) : unit
static member closeSync (fd: float) : unit
static member copyFileSync (src: PathLike, dest: PathLike, ?mode: float) : unit
static member cp (source: U2<string,URL>, destination: U2<string,URL>, opts: CopyOptions, callback: ErrnoException option -> unit) : unit
static member cp (source: U2<string,URL>, destination: U2<string,URL>, callback: ErrnoException option -> unit) : unit
static member cpSync (source: U2<string,URL>, destination: U2<string,URL>, ?opts: CopySyncOptions) : unit
static member createReadStream (path: PathLike, ?options: U2<string,ReadStreamOptions>) : ReadStream
static member createWriteStream (path: PathLike, ?options: U2<string,WriteStreamOptions>) : WriteStream
static member existsSync (path: PathLike) : bool
static member fchmodSync (fd: float, mode: Mode) : unit
static member fchownSync (fd: float, uid: float, gid: float) : unit
static member fdatasyncSync (fd: float) : unit
static member fstatSync (fd: float, ?options: StatOptions) : U2<BigIntStats,Stats>
static member fstatSync (fd: float, options: Options2) : BigIntStats
static member fstatSync (fd: float, ?options: Options) : Stats
static member fsyncSync (fd: float) : unit
static member ftruncateSync (fd: float, ?len: float) : unit
static member futimesSync (fd: float, atime: TimeLike, mtime: TimeLike) : unit
static member glob (pattern: U2<string,string array>, options: GlobOptions, callback: Callback4) : unit
static member glob (pattern: U2<string,string array>, options: GlobOptionsWithoutFileTypes, callback: Callback3) : unit
static member glob (pattern: U2<string,string array>, options: GlobOptionsWithFileTypes, callback: Callback2) : unit
static member glob (pattern: U2<string,string array>, callback: Callback) : unit
static member globSync (pattern: U2<string,string array>, options: GlobOptions) : U2<string array,Dirent<string> array>
static member globSync (pattern: U2<string,string array>, options: GlobOptionsWithoutFileTypes) : string array
static member globSync (pattern: U2<string,string array>, options: GlobOptionsWithFileTypes) : Dirent<string> array
static member globSync (pattern: U2<string,string array>) : string array
static member lchmodSync (path: PathLike, mode: Mode) : unit
static member lchownSync (path: PathLike, uid: float, gid: float) : unit
static member linkSync (existingPath: PathLike, newPath: PathLike) : unit
static member lutimesSync (path: PathLike, atime: TimeLike, mtime: TimeLike) : unit
static member mkdirSync (path: PathLike, ?options: U3<string,float,MakeDirectoryOptions>) : string option
static member mkdirSync (path: PathLike, ?options: U3<string,float,Options2>) : unit
static member mkdirSync (path: PathLike, options: Options) : string option
static member mkdtempSync (prefix: string, options: BufferEncodingOption) : NonSharedBuffer
static member mkdtempSync (prefix: string, ?options: EncodingOption) : string
static member openAsBlob (path: PathLike, ?options: OpenAsBlobOptions) : Promise<Blob>
static member openSync (path: PathLike, flags: OpenMode, ?mode: OpenMode) : float
static member opendirSync (path: PathLike, ?options: OpenDirOptions) : Dir
static member readFileSync (path: PathOrFileDescriptor, ?options: U2<string,Options3>) : U2<string,NonSharedBuffer>
static member readFileSync (path: PathOrFileDescriptor, options: U2<string,Options2>) : string
static member readFileSync (path: PathOrFileDescriptor, ?options: Options) : NonSharedBuffer
static member readSync (fd: float, buffer: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?opts: ReadOptions) : float
static member readSync (fd: float, buffer: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, offset: float, length: float, ?position: ReadPosition) : float
static member readdirSync (path: PathLike, options: Options5) : Dirent<NonSharedBuffer> array
static member readdirSync (path: PathLike, options: Options4) : Dirent<string> array
static member readdirSync (path: PathLike, ?options: U2<string,Options3>) : U2<string array,NonSharedBuffer array>
static member readdirSync (path: PathLike, options: U2<string,Options2>) : NonSharedBuffer array
static member readdirSync (path: PathLike, ?options: U2<string,Options>) : string array
static member readlinkSync (path: PathLike, options: BufferEncodingOption) : NonSharedBuffer
static member readlinkSync (path: PathLike, ?options: EncodingOption) : string
static member readvSync (fd: float, buffers: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>> array, ?position: float) : float
static member renameSync (oldPath: PathLike, newPath: PathLike) : unit
static member rmSync (path: PathLike, ?options: RmOptions) : unit
static member rmdirSync (path: PathLike, ?options: RmDirOptions) : unit
static member statfsSync (path: PathLike, ?options: StatFsOptions) : U2<BigIntStatsFs,StatsFs>
static member statfsSync (path: PathLike, options: Options2) : BigIntStatsFs
static member statfsSync (path: PathLike, ?options: Options) : StatsFs
static member symlinkSync (target: PathLike, path: PathLike, ?type: Type) : unit
static member truncateSync (path: PathLike, ?len: float) : unit
static member unlinkSync (path: PathLike) : unit
static member unwatchFile (filename: PathLike, ?listener: BigIntStatsListener) : unit
static member unwatchFile (filename: PathLike, ?listener: StatsListener) : unit
static member utimesSync (path: PathLike, atime: TimeLike, mtime: TimeLike) : unit
static member watch (filename: PathLike, listener: Listener) : FSWatcher
static member watch (filename: PathLike, options: U2<string,WatchOptions> option, listener: Listener3) : FSWatcher
static member watch (filename: PathLike, options: U2<string,WatchOptionsWithBufferEncoding>, listener: Listener2) : FSWatcher
static member watch (filename: PathLike, ?options: U2<string,WatchOptionsWithStringEncoding>, ?listener: Listener) : FSWatcher
static member watchFile (filename: PathLike, listener: StatsListener) : StatWatcher
static member watchFile (filename: PathLike, options: Options2 option, listener: BigIntStatsListener) : StatWatcher
static member watchFile (filename: PathLike, options: Options option, listener: StatsListener) : StatWatcher
static member writeFileSync (file: PathOrFileDescriptor, data: BinaryLike, ?options: U2<string,WriteFileOptions2>) : unit
static member writeSync (fd: float, string: string, ?position: float, ?encoding: BufferEncoding) : float
static member writeSync (fd: float, buffer: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?offset: float, ?length: float, ?position: float) : float
static member writevSync (fd: float, buffers: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>> array, ?position: float) : float| Assembly | Xantham.Fable.Node |
| Attributes | [<Erase>] |
The package's value exports, each bound to its import.
Properties
static member access: Access
static member access: AccessTests 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. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for possible values of mode.
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 if package.json exists, and if it is readable or writable.
import { access, constants } from 'node:fs';
const file = 'package.json';
// Check if the file exists in the current directory.
access(file, constants.F_OK, (err) => {
console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
});
// Check if the file is readable.
access(file, constants.R_OK, (err) => {
console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
});
// Check if the file is writable.
access(file, constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
});
// Check if the file is readable and writable.
access(file, constants.R_OK | constants.W_OK, (err) => {
console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);
});
Do not use fs.access() to check for the accessibility of a file before calling fs.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)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (!err) {
console.error('myfile already exists');
return;
}
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
write (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
read (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';
access('myfile', (err) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
});
read (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
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. Asynchronously tests a user's permissions for the file specified by path.
@since v0.11.15
| Parameter | |
|---|---|
path | A path to a file or directory. If a URL is provided, it must use the file: protocol. |
static member appendFile: AppendFile
static member appendFile: AppendFileAsynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.
The mode option only affects the newly created file. See open for more details.
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
If options is a string, then it specifies the encoding:
import { appendFile } from 'node:fs';
appendFile('message.txt', 'data to append', 'utf8', callback);
The path may be specified as a numeric file descriptor that has been opened for appending (using fs.open() or fs.openSync()). The file descriptor will not be closed automatically.
import { open, close, appendFile } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('message.txt', 'a', (err, fd) => {
if (err) throw err;
try {
appendFile(fd, 'data to append', 'utf8', (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
throw err;
}
});
Asynchronously append data to a file, creating the file if it does not exist.
@since v0.6.7
| Parameter | |
|---|---|
path | filename or file descriptor |
file | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
data | The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. |
static member chmod: Chmod
static member chmod: ChmodAsynchronously changes the permissions of a file. No arguments other than a possible exception are given to the completion callback.
See the POSIX chmod(2) documentation for more detail.
import { chmod } from 'node:fs';
chmod('my_file.txt', 0o775, (err) => {
if (err) throw err;
console.log('The permissions for file "my_file.txt" have been changed!');
});
@since v0.1.30
static member chown: Chown
static member chown: ChownAsynchronously changes owner and group of a file. No arguments other than a possible exception are given to the completion callback.
See the POSIX chown(2) documentation for more detail.
@since v0.1.97
static member close: Close
static member close: CloseCloses the file descriptor. No arguments other than a possible exception are given to the completion callback.
Calling fs.close() on any file descriptor (fd) that is currently in use through any other fs operation may lead to undefined behavior.
See the POSIX close(2) documentation for more detail.
@since v0.0.2
static member constants: Constants2static member copyFile: CopyFile
static member copyFile: CopyFileAsynchronously copies src to dest. By default, dest is overwritten if it already exists. No arguments other than a possible exception are given to the callback function. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFile, constants } from 'node:fs';
function callback(err) {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
}
// destination.txt will be created or overwritten by default.
copyFile('source.txt', 'destination.txt', callback);
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
@since v8.5.0
| Parameter | |
|---|---|
src | source filename to copy |
dest | destination filename of the copy operation |
mode | modifiers for copy operation. |
static member exists: Exists
static member exists: ExistsTest whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false:
import { exists } from 'node:fs';
exists('/etc/passwd', (e) => {
console.log(e ? 'it exists' : 'no passwd!');
});
The parameters for this callback are not consistent with other Node.jscallbacks. Normally, the first parameter to a Node.js callback is an err parameter, optionally followed by other parameters. The fs.exists() callback has only one boolean parameter. This is one reason fs.access() is recommended instead of fs.exists().
Using fs.exists() to check for the existence of a file before calling fs.open(), fs.readFile(), or fs.writeFile() is not recommended. 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 does not exist.
write (NOT RECOMMENDED)
import { exists, open, close } from 'node:fs';
exists('myfile', (e) => {
if (e) {
console.error('myfile already exists');
} else {
open('myfile', 'wx', (err, fd) => {
if (err) throw err;
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
}
});
write (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
try {
writeMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
read (NOT RECOMMENDED)
import { open, close, exists } from 'node:fs';
exists('myfile', (e) => {
if (e) {
open('myfile', 'r', (err, fd) => {
if (err) throw err;
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
} else {
console.error('myfile does not exist');
}
});
read (RECOMMENDED)
import { open, close } from 'node:fs';
open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === 'ENOENT') {
console.error('myfile does not exist');
return;
}
throw err;
}
try {
readMyData(fd);
} finally {
close(fd, (err) => {
if (err) throw err;
});
}
});
The "not recommended" examples above check for existence 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 existence of a file only if the file won't be used directly, for example when its existence is a signal from another process.
@since v0.0.2
static member fchmod: Fchmod
static member fchmod: FchmodSets the permissions on the file. No arguments other than a possible exception are given to the completion callback.
See the POSIX fchmod(2) documentation for more detail.
@since v0.4.7
static member fchown: Fchown
static member fchown: FchownSets the owner of the file. No arguments other than a possible exception are given to the completion callback.
See the POSIX fchown(2) documentation for more detail.
@since v0.4.7
static member fdatasync: Fdatasync
static member fdatasync: FdatasyncForces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. No arguments other than a possible exception are given to the completion callback.
@since v0.1.96
static member fstat: Fstat
static member fstat: FstatInvokes the callback with the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
@since v0.1.95
static member fsync: Fsync
static member fsync: FsyncRequest that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback.
@since v0.1.96
static member ftruncate: Ftruncate
static member ftruncate: FtruncateTruncates the file descriptor. No arguments other than a possible exception are given to the completion callback.
See the POSIX ftruncate(2) documentation for more detail.
If the file referred to by the file descriptor was larger than len bytes, only the first len bytes will be retained in the file.
For example, the following program retains only the first four bytes of the file:
import { open, close, ftruncate } from 'node:fs';
function closeFd(fd) {
close(fd, (err) => {
if (err) throw err;
});
}
open('temp.txt', 'r+', (err, fd) => {
if (err) throw err;
try {
ftruncate(fd, 4, (err) => {
closeFd(fd);
if (err) throw err;
});
} catch (err) {
closeFd(fd);
if (err) throw err;
}
});
If the file previously was shorter than len bytes, it is extended, and the extended part is filled with null bytes ('\0'):
If len is negative then 0 will be used. Asynchronous ftruncate(2) - Truncate a file to a specified length.
@since v0.8.6
| Parameter | |
|---|---|
fd | A file descriptor. |
static member futimes: Futimes
static member futimes: FutimesChange the file system timestamps of the object referenced by the supplied file descriptor. See utimes.
@since v0.4.2
static member lchmod: Lchmod
static member lchmod: LchmodChanges the permissions on a symbolic link. No arguments other than a possible exception are given to the completion callback.
This method is only implemented on macOS.
See the POSIX lchmod(2) documentation for more detail.
@deprecated Since v0.4.7
static member lchown: Lchown
static member lchown: LchownSet the owner of the symbolic link. No arguments other than a possible exception are given to the completion callback.
See the POSIX lchown(2) documentation for more detail.
static member link: Link
static member link: LinkCreates a new link from the existingPath to the newPath. See the POSIX link(2) documentation for more detail. No arguments other than a possible exception are given to the completion callback.
@since v0.1.31
static member lstat: Lstat
static member lstat: LstatRetrieves the fs.Stats for the symbolic link referred to by the path. The callback gets two arguments (err, stats) where stats is a fs.Stats object. lstat() is identical to stat(), except that if path is a symbolic link, then the link itself is stat-ed, not the file that it refers to.
See the POSIX lstat(2) documentation for more details.
@since v0.1.30
static member lstatSync: StatSyncFn
static member lstatSync: StatSyncFnSynchronous lstat(2) - Get file status. Does not dereference symbolic links.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
static member lutimes: Lutimes
static member lutimes: LutimesChanges the access and modification times of a file in the same way as utimes, with the difference that if the path refers to a symbolic link, then the link is not dereferenced: instead, the timestamps of the symbolic link itself are changed.
No arguments other than a possible exception are given to the completion callback.
@since v14.5.0, v12.19.0
static member mkdir: Mkdir
static member mkdir: MkdirAsynchronously creates a directory.
The callback is given a possible exception and, if recursive is true, the first directory path created, (err[, path]).path can still be undefined when recursive is true, if no directory was created (for instance, if it was previously created).
The optional options argument can be an integer specifying mode (permission and sticky bits), or an object with a mode property and a recursive property indicating whether parent directories should be created. Calling fs.mkdir() when path is a directory that exists results in an error only when recursive is false. If recursive is false and the directory exists, an EEXIST error occurs.
import { mkdir } from 'node:fs';
// Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist.
mkdir('./tmp/a/apple', { recursive: true }, (err) => {
if (err) throw err;
});
On Windows, using fs.mkdir() on the root directory even with recursion will result in an error:
import { mkdir } from 'node:fs';
mkdir('/', { recursive: true }, (err) => {
// => [Error: EPERM: operation not permitted, mkdir 'C:\']
});
See the POSIX mkdir(2) documentation for more details. Asynchronous mkdir(2) - create a directory. Asynchronous mkdir(2) - create a directory with a mode of 0o777.
@since v0.1.8
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
static member mkdtemp: Mkdtemp
static member mkdtemp: MkdtempCreates a unique temporary directory.
Generates six random characters to be appended behind a required prefix to create a unique temporary directory. Due to platform inconsistencies, avoid trailing X characters in prefix. Some platforms, notably the BSDs, can return more than six random characters, and replace trailing X characters in prefix with random characters.
The created directory path is passed as a string to the callback's second parameter.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use.
import { mkdtemp } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => {
if (err) throw err;
console.log(directory);
// Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
});
The fs.mkdtemp() method will append the six randomly selected characters directly to the prefix string. For instance, given a directory /tmp, if the intention is to create a temporary directory within/tmp, the prefixmust end with a trailing platform-specific path separator (import { sep } from 'node:path').
import { tmpdir } from 'node:os';
import { mkdtemp } from 'node:fs';
// The parent directory for the new temporary directory
const tmpDir = tmpdir();
// This method is *INCORRECT*:
mkdtemp(tmpDir, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmpabc123`.
// A new temporary directory is created at the file system root
// rather than *within* the /tmp directory.
});
// This method is *CORRECT*:
import { sep } from 'node:path';
mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
if (err) throw err;
console.log(directory);
// Will print something similar to `/tmp/abc123`.
// A new temporary directory is created within
// the /tmp directory.
});
Asynchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
@since v5.10.0
| Parameter | |
|---|---|
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
static member open: Open
static member open: OpenAsynchronous file open. See the POSIX open(2) documentation for more details.
mode sets the file mode (permission and sticky bits), but only if the file was created. On Windows, only the write permission can be manipulated; see chmod.
The callback gets two arguments (err, fd).
Some characters (< > : " / \ | ? *) are reserved under Windows as documented by Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains a colon, Node.js will open a file system stream, as described by this MSDN page.
Functions based on fs.open() exhibit this behavior as well:fs.writeFile(), fs.readFile(), etc. Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be 0o666.
@since v0.0.2
| Parameter | |
|---|---|
flags | See support of file system flags``. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
flags | See support of file system flags``. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
static member opendir: Opendir
static member opendir: OpendirAsynchronously open a directory. See the POSIX opendir(3) documentation for more details.
Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.
The encoding option sets the encoding for the path while opening the directory and subsequent read operations.
@since v12.12.0
static member read: Read
static member read: ReadRead data from the file specified by fd.
The callback is given the three arguments, (err, bytesRead, buffer).
If the file is not modified concurrently, the end-of-file is reached when the number of bytes read is zero.
If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesRead and buffer properties. Similar to the above fs.read function, this version takes an optional options object. If not otherwise specified in an options object, buffer defaults to Buffer.alloc(16384), offset defaults to 0, length defaults to buffer.byteLength, - offset as of Node 17.6.0 position defaults to null
@since v0.0.2
| Parameter | |
|---|---|
buffer | The buffer that the data will be written to. |
offset | The position in buffer to write the data to. |
length | The number of bytes to read. |
position | Specifies where to begin reading from in the file. If position is null or -1 , data will be read from the current file position, and the file position will be updated. If position is an integer, the file position will be unchanged. |
static member readFile: ReadFile
static member readFile: ReadFileAsynchronously reads the entire contents of a file.
import { readFile } from 'node:fs';
readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
The callback is passed two arguments (err, data), where data is the contents of the file.
If no encoding is specified, then the raw buffer is returned.
If options is a string, then it specifies the encoding:
import { readFile } from 'node:fs';
readFile('/etc/passwd', 'utf8', callback);
When the path is a directory, the behavior of fs.readFile() and readFileSync is platform-specific. On macOS, Linux, and Windows, an error will be returned. On FreeBSD, a representation of the directory's contents will be returned.
import { readFile } from 'node:fs';
// macOS, Linux, and Windows
readFile('<directory>', (err, data) => {
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
});
// FreeBSD
readFile('<directory>', (err, data) => {
// => null, <data>
});
It is possible to abort an ongoing request using an AbortSignal. If a request is aborted the callback is called with an AbortError:
import { readFile } from 'node:fs';
const controller = new AbortController();
const signal = controller.signal;
readFile(fileInfo[0].name, { signal }, (err, buf) => {
// ...
});
// When you want to abort the request
controller.abort();
The fs.readFile() function buffers the entire file. To minimize memory costs, when possible prefer streaming via fs.createReadStream().
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.readFile performs. Asynchronously reads the entire contents of a file.
@since v0.1.29
| Parameter | |
|---|---|
path | filename or file descriptor |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
options | Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'. |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
options | Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'. |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
static member readdir: Readdir
static member readdir: ReaddirReads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames passed to the callback. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the files array will contain fs.Dirent objects. Asynchronous readdir(3) - read a directory.
@since v0.1.8
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | If called with withFileTypes: true the result data will be an array of Dirent. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Must include withFileTypes: true and encoding: 'buffer'. |
static member readlink: Readlink
static member readlink: ReadlinkReads the contents of the symbolic link referred to by path. The callback gets two arguments (err, linkString).
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the link path passed to the callback. If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object. Asynchronous readlink(2) - read value of a symbolic link.
@since v0.1.31
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
static member readv: Readv
static member readv: ReadvRead from a file specified by fd and write to an array of ArrayBufferViews using readv().
position is the offset from the beginning of the file from where data should be read. If typeof position !== 'number', the data will be read from the current position.
The callback will be given three arguments: err, bytesRead, and buffers. bytesRead is how many bytes were read from the file.
If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesRead and buffers properties.
@since v13.13.0, v12.17.0
static member realpath: Realpath
static member realpath: RealpathAsynchronously computes the canonical pathname by resolving ., .., and symbolic links.
A canonical pathname is not necessarily unique. Hard links and bind mounts can expose a file system entity through many pathnames.
This function behaves like realpath(3), with some exceptions:
- No case conversion is performed on case-insensitive file systems.
- The maximum number of symbolic links is platform-independent and generally (much) higher than what the native
realpath(3)implementation supports.
The callback gets two arguments (err, resolvedPath). May use process.cwd to resolve relative paths.
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the path passed to the callback. If the encoding is set to 'buffer', the path returned will be passed as a Buffer object.
If path resolves to a socket or a pipe, the function will return a system dependent name for that object. Asynchronous realpath(3) - return the canonicalized absolute pathname.
@since v0.1.31
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
static member realpathSync: RealpathSync
static member realpathSync: RealpathSyncReturns the resolved pathname.
For detailed information, see the documentation of the asynchronous version of this API: realpath. Synchronous realpath(3) - return the canonicalized absolute pathname.
@since v0.1.31
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
static member rename: Rename
static member rename: RenameAsynchronously rename file at oldPath to the pathname provided as newPath. In the case that newPath already exists, it will be overwritten. If there is a directory at newPath, an error will be raised instead. No arguments other than a possible exception are given to the completion callback.
See also: rename(2).
import { rename } from 'node:fs';
rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) throw err;
console.log('Rename complete!');
});
@since v0.0.2
static member rm: Rm
static member rm: RmAsynchronously removes files and directories (modeled on the standard POSIX rm utility). No arguments other than a possible exception are given to the completion callback.
@since v14.14.0
static member rmdir: Rmdir
static member rmdir: RmdirAsynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.
Using fs.rmdir() on a file (not a directory) results in an ENOENT error on Windows and an ENOTDIR error on POSIX.
To get a behavior similar to the rm -rf Unix command, use rm with options { recursive: true, force: true }.
@since v0.0.2
static member stat: Stat
static member stat: StatAsynchronous stat(2). The callback gets two arguments (err, stats) wherestats is an fs.Stats object.
In case of an error, the err.code will be one of Common System Errors.
stat follows symbolic links. Use lstat to look at the links themselves.
Using fs.stat() to check for the existence of a file before callingfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.
To check if a file exists without manipulating it afterwards, access is recommended.
For example, given the following directory structure:
- txtDir
-- file.txt
- app.js
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';
const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
for (let i = 0; i < pathsToCheck.length; i++) {
stat(pathsToCheck[i], (err, stats) => {
console.log(stats.isDirectory());
console.log(stats);
});
}
The resulting output will resemble:
true
Stats {
dev: 16777220,
mode: 16877,
nlink: 3,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214262,
size: 96,
blocks: 0,
atimeMs: 1561174653071.963,
mtimeMs: 1561174614583.3518,
ctimeMs: 1561174626623.5366,
birthtimeMs: 1561174126937.2893,
atime: 2019-06-22T03:37:33.072Z,
mtime: 2019-06-22T03:36:54.583Z,
ctime: 2019-06-22T03:37:06.624Z,
birthtime: 2019-06-22T03:28:46.937Z
}
false
Stats {
dev: 16777220,
mode: 33188,
nlink: 1,
uid: 501,
gid: 20,
rdev: 0,
blksize: 4096,
ino: 14214074,
size: 8,
blocks: 8,
atimeMs: 1561174616618.8555,
mtimeMs: 1561174614584,
ctimeMs: 1561174614583.8145,
birthtimeMs: 1561174007710.7478,
atime: 2019-06-22T03:36:56.619Z,
mtime: 2019-06-22T03:36:54.584Z,
ctime: 2019-06-22T03:36:54.584Z,
birthtime: 2019-06-22T03:26:47.711Z
}
@since v0.0.2
static member statSync: StatSyncFn
static member statSync: StatSyncFnSynchronous stat(2) - Get file status.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
static member statfs: Statfs
static member statfs: StatfsAsynchronous statfs(2). Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where statsis an fs.StatFs object.
In case of an error, the err.code will be one of Common System Errors.
@since v19.6.0, v18.15.0
| Parameter | |
|---|---|
path | A path to an existing file or directory on the file system to be queried. |
static member symlink: Symlink
static member symlink: SymlinkCreates the link called path pointing to target. No arguments other than a possible exception are given to the completion callback.
See the POSIX symlink(2) documentation for more details.
The type argument is only available on Windows and ignored on other platforms. It can be set to 'dir', 'file', or 'junction'. If the type argument is not a string, Node.js will autodetect target type and use 'file' or 'dir'. If the target does not exist, 'file' will be used. Windows junction points require the destination path to be absolute. When using 'junction', thetarget argument will automatically be normalized to absolute path. Junction points on NTFS volumes can only point to directories.
Relative targets are relative to the link's parent directory.
import { symlink } from 'node:fs';
symlink('./mew', './mewtwo', callback);
The above example creates a symbolic link mewtwo which points to mew in the same directory:
$ tree .
.
โโโ mew
โโโ mewtwo -> ./mew
Asynchronous symlink(2) - Create a new symbolic link to an existing file.
@since v0.1.31
| Parameter | |
|---|---|
target | A path to an existing file. If a URL is provided, it must use the file: protocol. |
path | A path to the new symlink. If a URL is provided, it must use the file: protocol. |
static member truncate: Truncate
static member truncate: TruncateTruncates the file. No arguments other than a possible exception are given to the completion callback. A file descriptor can also be passed as the first argument. In this case, fs.ftruncate() is called.
import { truncate } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
truncate('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was truncated');
});
Passing a file descriptor is deprecated and may result in an error being thrown in the future.
See the POSIX truncate(2) documentation for more details. Asynchronous truncate(2) - Truncate a file to a specified length.
@since v0.8.6
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
static member unlink: Unlink
static member unlink: UnlinkAsynchronously removes a file or symbolic link. No arguments other than a possible exception are given to the completion callback.
import { unlink } from 'node:fs';
// Assuming that 'path/file.txt' is a regular file.
unlink('path/file.txt', (err) => {
if (err) throw err;
console.log('path/file.txt was deleted');
});
fs.unlink() will not work on a directory, empty or otherwise. To remove a directory, use rmdir.
See the POSIX unlink(2) documentation for more details.
@since v0.0.2
static member utimes: Utimes
static member utimes: UtimesChange the file system timestamps of the object referenced by path.
The atime and mtime arguments follow these rules:
- Values can be either numbers representing Unix epoch time in seconds,
Dates, or a numeric string like'123456789.0'. - If the value can not be converted to a number, or is
NaN,Infinity, or-Infinity, anErrorwill be thrown.
@since v0.4.2
static member write: Write
static member write: WriteWrite buffer to the file specified by fd.
offset determines the part of the buffer to be written, and length is an integer specifying the number of bytes to write.
position refers to the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position. See pwrite(2).
The callback will be given three arguments (err, bytesWritten, buffer) where bytesWritten specifies how many bytes were written from buffer.
If this method is invoked as its util.promisify() ed version, it returns a promise for an Object with bytesWritten and buffer properties.
It is unsafe to use fs.write() multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. Asynchronously writes buffer to the file referenced by the supplied file descriptor. Asynchronously writes string to the file referenced by the supplied file descriptor.
@since v0.0.2
| Parameter | |
|---|---|
fd | A file descriptor. |
offset | The part of the buffer to be written. If not supplied, defaults to 0. |
length | The number of bytes to write. If not supplied, defaults to buffer.length - offset. |
fd | A file descriptor. |
offset | The part of the buffer to be written. If not supplied, defaults to 0. |
fd | A file descriptor. |
fd | A file descriptor. |
options | An object with the following properties: * offset The part of the buffer to be written. If not supplied, defaults to 0. * length The number of bytes to write. If not supplied, defaults to buffer.length - offset. * position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. |
fd | A file descriptor. |
string | A string to write. |
position | The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. |
encoding | The expected string encoding. |
fd | A file descriptor. |
string | A string to write. |
position | The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. |
fd | A file descriptor. |
string | A string to write. |
static member writeFile: WriteFile
static member writeFile: WriteFileWhen file is a filename, asynchronously writes data to the file, replacing the file if it 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 (which is recommended). See the notes below on using a file descriptor.
The encoding option is ignored if data is a buffer.
The mode option only affects the newly created file. See open for more details.
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
If options is a string, then it specifies the encoding:
import { writeFile } from 'node:fs';
writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
It is unsafe to use fs.writeFile() multiple times on the same file without waiting for the callback. For this scenario, createWriteStream is recommended.
Similarly to fs.readFile - fs.writeFile is a convenience method that performs multiple write calls internally to write the buffer passed to it. For performance sensitive code consider using createWriteStream.
It is possible to use an AbortSignal to cancel an fs.writeFile(). Cancelation is "best effort", and some amount of data is likely still to be written.
import { writeFile } from 'node:fs';
import { Buffer } from 'node:buffer';
const controller = new AbortController();
const { signal } = controller;
const data = new Uint8Array(Buffer.from('Hello Node.js'));
writeFile('message.txt', data, { signal }, (err) => {
// When a request is aborted - the callback is called with an AbortError
});
// When the request should be aborted
controller.abort();
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.writeFile performs. Asynchronously writes data to a file, replacing the file if it already exists.
@since v0.1.29
| Parameter | |
|---|---|
file | filename or file descriptor |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
data | The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. |
static member writev: Writev2
static member writev: Writev2Write an array of ArrayBufferViews to the file specified by fd using writev().
position is the offset from the beginning of the file where this data should be written. If typeof position !== 'number', the data will be written at the current position.
The callback will be given three arguments: err, bytesWritten, and buffers. bytesWritten is how many bytes were written from buffers.
If this method is util.promisify() ed, it returns a promise for an Object with bytesWritten and buffers properties.
It is unsafe to use fs.writev() multiple times on the same file without waiting for the callback. For this scenario, use createWriteStream.
On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file.
@since v12.9.0
Methods
static member Dir () : Dir
static member Dir () : DirA class representing a directory stream.
Created by opendir, opendirSync, or fsPromises.opendir().
import { opendir } from 'node:fs/promises';
try {
const dir = await opendir('./');
for await (const dirent of dir)
console.log(dirent.name);
} catch (err) {
console.error(err);
}
When using the async iterator, the fs.Dir object will be automatically closed after the iterator exits.
@since v12.12.0
static member Dirent<'Name> () : Dirent<'Name>
static member Dirent<'Name> () : Dirent<'Name>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 readdir or readdirSync is called with the withFileTypes option set to true, the resulting array is filled with fs.Dirent objects, rather than strings or Buffer s.
@since v10.10.0
static member ReadStream (?opts: ReadableOptions<Readable>) : ReadStream
static member ReadStream (?opts: ReadableOptions<Readable>) : ReadStreamInstances of fs.ReadStream are created and returned using the createReadStream function.
@since v0.1.93
static member StatsFs () : StatsFs
static member StatsFs () : StatsFsProvides information about a mounted file system.
Objects returned from statfs and its synchronous counterpart are of this type. If bigint in the options passed to those methods is true, the numeric values will be bigint instead of number.
StatFs {
type: 1397114950,
bsize: 4096,
blocks: 121938943,
bfree: 61058895,
bavail: 61058895,
files: 999,
ffree: 1000000
}
bigint version:
StatFs {
type: 1397114950n,
bsize: 4096n,
blocks: 121938943n,
bfree: 61058895n,
bavail: 61058895n,
files: 999n,
ffree: 1000000n
}
@since v19.6.0, v18.15.0
static member WriteStream (?opts: WritableOptions<Writable>) : WriteStream
static member WriteStream (?opts: WritableOptions<Writable>) : WriteStream- Extends
stream.Writable
Instances of fs.WriteStream are created and returned using the createWriteStream function.
@since v0.1.93
static member accessSync (path: PathLike, ?mode: float) : unit
static member accessSync (path: PathLike, ?mode: float) : unitSynchronously 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. mode should be either the value fs.constants.F_OK or a mask consisting of the bitwise OR of any of fs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). Check File access constants for possible values of mode.
If any of the accessibility checks fail, an Error will be thrown. Otherwise, the method will return undefined.
import { accessSync, constants } from 'node:fs';
try {
accessSync('etc/passwd', constants.R_OK | constants.W_OK);
console.log('can read/write');
} catch (err) {
console.error('no access!');
}
@since v0.11.15
static member appendFileSync (path: PathOrFileDescriptor, data: U2<string,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>>, ?options: U2<string,WriteFileOptions2>) : unit
static member appendFileSync (path: PathOrFileDescriptor, data: U2<string,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>>, ?options: U2<string,WriteFileOptions2>) : unitSynchronously append data to a file, creating the file if it does not yet exist. data can be a string or a Buffer.
The mode option only affects the newly created file. See open for more details.
import { appendFileSync } from 'node:fs';
try {
appendFileSync('message.txt', 'data to append');
console.log('The "data to append" was appended to file!');
} catch (err) {
// Handle the error
}
If options is a string, then it specifies the encoding:
import { appendFileSync } from 'node:fs';
appendFileSync('message.txt', 'data to append', 'utf8');
The path may be specified as a numeric file descriptor that has been opened for appending (using fs.open() or fs.openSync()). The file descriptor will not be closed automatically.
import { openSync, closeSync, appendFileSync } from 'node:fs';
let fd;
try {
fd = openSync('message.txt', 'a');
appendFileSync(fd, 'data to append', 'utf8');
} catch (err) {
// Handle the error
} finally {
if (fd !== undefined)
closeSync(fd);
}
@since v0.6.7
| Parameter | |
|---|---|
path | filename or file descriptor |
static member closeSync (fd: float) : unit
static member closeSync (fd: float) : unitCloses the file descriptor. Returns undefined.
Calling fs.closeSync() on any file descriptor (fd) that is currently in use through any other fs operation may lead to undefined behavior.
See the POSIX close(2) documentation for more detail.
@since v0.1.21
static member copyFileSync (src: PathLike, dest: PathLike, ?mode: float) : unit
static member copyFileSync (src: PathLike, dest: PathLike, ?mode: float) : unitSynchronously copies src to dest. By default, dest is overwritten if it already exists. Returns undefined. Node.js makes no guarantees about the atomicity of the copy operation. If an error occurs after the destination file has been opened for writing, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then a fallback copy mechanism is used.fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt to create a copy-on-write reflink. If the platform does not support copy-on-write, then the operation will fail.
import { copyFileSync, constants } from 'node:fs';
// destination.txt will be created or overwritten by default.
copyFileSync('source.txt', 'destination.txt');
console.log('source.txt was copied to destination.txt');
// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
@since v8.5.0
| Parameter | |
|---|---|
src | source filename to copy |
dest | destination filename of the copy operation |
mode | modifiers for copy operation. |
static member cp (source: U2<string,URL>, destination: U2<string,URL>, opts: CopyOptions, callback: ErrnoException option -> unit) : unit
static member cp (source: U2<string,URL>, destination: U2<string,URL>, opts: CopyOptions, callback: ErrnoException option -> unit) : unitAsynchronously copies the entire directory structure from src to dest, including subdirectories and files.
When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.
@since v16.7.0
| Parameter | |
|---|---|
src | source path to copy. |
dest | destination path to copy to. |
static member cp (source: U2<string,URL>, destination: U2<string,URL>, callback: ErrnoException option -> unit) : unit
static member cp (source: U2<string,URL>, destination: U2<string,URL>, callback: ErrnoException option -> unit) : unitAsynchronously copies the entire directory structure from src to dest, including subdirectories and files.
When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.
@since v16.7.0
| Parameter | |
|---|---|
src | source path to copy. |
dest | destination path to copy to. |
static member cpSync (source: U2<string,URL>, destination: U2<string,URL>, ?opts: CopySyncOptions) : unit
static member cpSync (source: U2<string,URL>, destination: U2<string,URL>, ?opts: CopySyncOptions) : unitSynchronously copies the entire directory structure from src to dest, including subdirectories and files.
When copying a directory to another directory, globs are not supported and behavior is similar to cp dir1/ dir2/.
@since v16.7.0
| Parameter | |
|---|---|
src | source path to copy. |
dest | destination path to copy to. |
static member createReadStream (path: PathLike, ?options: U2<string,ReadStreamOptions>) : ReadStream
static member createReadStream (path: PathLike, ?options: U2<string,ReadStreamOptions>) : ReadStreamoptions can include start and end values to read a range of bytes from the file instead of the entire file. Both start and end are inclusive and start counting at 0, allowed values are in the \0, [Number.MAX_SAFE_INTEGER] range. If fd is specified and start is omitted or undefined, fs.createReadStream() reads sequentially from the current file position. The encoding can be any one of those accepted by Buffer.
If fd is specified, ReadStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.
If fd points to a character device that only supports blocking reads (such as keyboard or sound card), read operations do not finish until data is available. This can prevent the process from exiting and the stream from closing naturally.
By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.
By providing the fs option, it is possible to override the corresponding fs implementations for open, read, and close. When providing the fs option, an override for read is required. If no fd is provided, an override for open is also required. If autoClose is true, an override for close is also required.
import { createReadStream } from 'node:fs';
// Create a stream from some character device.
const stream = createReadStream('/dev/input/event0');
setTimeout(() => {
stream.close(); // This may not close the stream.
// Artificially marking end-of-stream, as if the underlying resource had
// indicated end-of-file by itself, allows the stream to close.
// This does not cancel pending read operations, and if there is such an
// operation, the process may still not be able to exit successfully
// until it finishes.
stream.push(null);
stream.read(0);
}, 100);
If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak. If autoClose is set to true (default behavior), on 'error' or 'end' the file descriptor will be closed automatically.
mode sets the file mode (permission and sticky bits), but only if the file was created.
An example to read the last 10 bytes of a file which is 100 bytes long:
import { createReadStream } from 'node:fs';
createReadStream('sample.txt', { start: 90, end: 99 });
If options is a string, then it specifies the encoding.
@since v0.1.31
static member createWriteStream (path: PathLike, ?options: U2<string,WriteStreamOptions>) : WriteStream
static member createWriteStream (path: PathLike, ?options: U2<string,WriteStreamOptions>) : WriteStreamoptions may also include a start option to allow writing data at some position past the beginning of the file, allowed values are in the \0, [Number.MAX_SAFE_INTEGER] range. Modifying a file rather than replacing it may require the flags option to be set to r+ rather than the default w. The encoding can be any one of those accepted by Buffer.
If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error. It is the application's responsibility to close it and make sure there's no file descriptor leak.
By default, the stream will emit a 'close' event after it has been destroyed. Set the emitClose option to false to change this behavior.
By providing the fs option it is possible to override the corresponding fs implementations for open, write, writev, and close. Overriding write() without writev() can reduce performance as some optimizations (_writev()) will be disabled. When providing the fs option, overrides for at least one of write and writev are required. If no fd option is supplied, an override for open is also required. If autoClose is true, an override for close is also required.
Like fs.ReadStream, if fd is specified, fs.WriteStream will ignore the path argument and will use the specified file descriptor. This means that no 'open' event will be emitted. fd should be blocking; non-blocking fds should be passed to net.Socket.
If options is a string, then it specifies the encoding.
@since v0.1.31
static member existsSync (path: PathLike) : bool
static member existsSync (path: PathLike) : boolReturns true if the path exists, false otherwise.
For detailed information, see the documentation of the asynchronous version of this API: exists.
fs.exists() is deprecated, but fs.existsSync() is not. The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.
import { existsSync } from 'node:fs';
if (existsSync('/etc/passwd'))
console.log('The path exists.');
@since v0.1.21
static member fchmodSync (fd: float, mode: Mode) : unit
static member fchmodSync (fd: float, mode: Mode) : unitSets the permissions on the file. Returns undefined.
See the POSIX fchmod(2) documentation for more detail.
@since v0.4.7
static member fchownSync (fd: float, uid: float, gid: float) : unit
static member fchownSync (fd: float, uid: float, gid: float) : unitSets the owner of the file. Returns undefined.
See the POSIX fchown(2) documentation for more detail.
@since v0.4.7
| Parameter | |
|---|---|
uid | The file's new owner's user id. |
gid | The file's new group's group id. |
static member fdatasyncSync (fd: float) : unit
static member fdatasyncSync (fd: float) : unitForces all currently queued I/O operations associated with the file to the operating system's synchronized I/O completion state. Refer to the POSIX fdatasync(2) documentation for details. Returns undefined.
@since v0.1.96
static member fstatSync (fd: float, ?options: StatOptions) : U2<BigIntStats,Stats>
static member fstatSync (fd: float, ?options: StatOptions) : U2<BigIntStats,Stats>Retrieves the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
@since v0.1.95
static member fstatSync (fd: float, options: Options2) : BigIntStats
static member fstatSync (fd: float, options: Options2) : BigIntStatsRetrieves the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
@since v0.1.95
static member fstatSync (fd: float, ?options: Options) : Stats
static member fstatSync (fd: float, ?options: Options) : StatsRetrieves the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
@since v0.1.95
static member fsyncSync (fd: float) : unit
static member fsyncSync (fd: float) : unitRequest that all data for the open file descriptor is flushed to the storage device. The specific implementation is operating system and device specific. Refer to the POSIX fsync(2) documentation for more detail. Returns undefined.
@since v0.1.96
static member ftruncateSync (fd: float, ?len: float) : unit
static member ftruncateSync (fd: float, ?len: float) : unitTruncates the file descriptor. Returns undefined.
For detailed information, see the documentation of the asynchronous version of this API: ftruncate.
@since v0.8.6
static member futimesSync (fd: float, atime: TimeLike, mtime: TimeLike) : unit
static member futimesSync (fd: float, atime: TimeLike, mtime: TimeLike) : unitSynchronous version of futimes. Returns undefined.
@since v0.4.2
static member glob (pattern: U2<string,string array>, options: GlobOptions, callback: Callback4) : unit
static member glob (pattern: U2<string,string array>, options: GlobOptions, callback: Callback4) : unitRetrieves the files matching the specified pattern.
import { glob } from 'node:fs';
glob('*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
@since v22.0.0
static member glob (pattern: U2<string,string array>, options: GlobOptionsWithoutFileTypes, callback: Callback3) : unit
static member glob (pattern: U2<string,string array>, options: GlobOptionsWithoutFileTypes, callback: Callback3) : unitRetrieves the files matching the specified pattern.
import { glob } from 'node:fs';
glob('*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
@since v22.0.0
static member glob (pattern: U2<string,string array>, options: GlobOptionsWithFileTypes, callback: Callback2) : unit
static member glob (pattern: U2<string,string array>, options: GlobOptionsWithFileTypes, callback: Callback2) : unitRetrieves the files matching the specified pattern.
import { glob } from 'node:fs';
glob('*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
@since v22.0.0
static member glob (pattern: U2<string,string array>, callback: Callback) : unit
static member glob (pattern: U2<string,string array>, callback: Callback) : unitRetrieves the files matching the specified pattern.
import { glob } from 'node:fs';
glob('*.js', (err, matches) => {
if (err) throw err;
console.log(matches);
});
@since v22.0.0
static member globSync (pattern: U2<string,string array>, options: GlobOptions) : U2<string array,Dirent<string> array>
static member globSync (pattern: U2<string,string array>, options: GlobOptions) : U2<string array,Dirent<string> array>import { globSync } from 'node:fs';
console.log(globSync('*.js'));
@since v22.0.0
Returns. paths of files that match the pattern.
static member globSync (pattern: U2<string,string array>, options: GlobOptionsWithoutFileTypes) : string array
static member globSync (pattern: U2<string,string array>, options: GlobOptionsWithoutFileTypes) : string arrayimport { globSync } from 'node:fs';
console.log(globSync('*.js'));
@since v22.0.0
Returns. paths of files that match the pattern.
static member globSync (pattern: U2<string,string array>, options: GlobOptionsWithFileTypes) : Dirent<string> array
static member globSync (pattern: U2<string,string array>, options: GlobOptionsWithFileTypes) : Dirent<string> arrayimport { globSync } from 'node:fs';
console.log(globSync('*.js'));
@since v22.0.0
Returns. paths of files that match the pattern.
static member globSync (pattern: U2<string,string array>) : string array
static member globSync (pattern: U2<string,string array>) : string arrayimport { globSync } from 'node:fs';
console.log(globSync('*.js'));
@since v22.0.0
Returns. paths of files that match the pattern.
static member lutimesSync (path: PathLike, atime: TimeLike, mtime: TimeLike) : unit
static member lutimesSync (path: PathLike, atime: TimeLike, mtime: TimeLike) : unitChange the file system timestamps of the symbolic link referenced by path. Returns undefined, or throws an exception when parameters are incorrect or the operation fails. This is the synchronous version of lutimes.
@since v14.5.0, v12.19.0
static member mkdirSync (path: PathLike, ?options: U3<string,float,MakeDirectoryOptions>) : string option
static member mkdirSync (path: PathLike, ?options: U3<string,float,MakeDirectoryOptions>) : string optionSynchronously creates a directory. Returns undefined, or if recursive is true, the first directory path created. This is the synchronous version of mkdir.
See the POSIX mkdir(2) documentation for more details. Synchronous mkdir(2) - create a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
static member mkdirSync (path: PathLike, ?options: U3<string,float,Options2>) : unit
static member mkdirSync (path: PathLike, ?options: U3<string,float,Options2>) : unitSynchronously creates a directory. Returns undefined, or if recursive is true, the first directory path created. This is the synchronous version of mkdir.
See the POSIX mkdir(2) documentation for more details. Synchronous mkdir(2) - create a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Either the file mode, or an object optionally specifying the file mode and whether parent folders should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to 0o777. |
static member mkdirSync (path: PathLike, options: Options) : string option
static member mkdirSync (path: PathLike, options: Options) : string optionSynchronously creates a directory. Returns undefined, or if recursive is true, the first directory path created. This is the synchronous version of mkdir.
See the POSIX mkdir(2) documentation for more details. Synchronous mkdir(2) - create a directory.
@since v0.1.21
static member mkdtempSync (prefix: string, options: BufferEncodingOption) : NonSharedBuffer
static member mkdtempSync (prefix: string, options: BufferEncodingOption) : NonSharedBufferReturns the created directory path.
For detailed information, see the documentation of the asynchronous version of this API: mkdtemp.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use. Synchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
| Parameter | |
|---|---|
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
static member mkdtempSync (prefix: string, ?options: EncodingOption) : string
static member mkdtempSync (prefix: string, ?options: EncodingOption) : stringReturns the created directory path.
For detailed information, see the documentation of the asynchronous version of this API: mkdtemp.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use. Synchronously creates a unique temporary directory. Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
@since v5.10.0
static member openAsBlob (path: PathLike, ?options: OpenAsBlobOptions) : Promise<Blob>
static member openAsBlob (path: PathLike, ?options: OpenAsBlobOptions) : Promise<Blob>Returns a Blob whose data is backed by the given file.
The file must not be modified after the Blob is created. Any modifications will cause reading the Blob data to fail with a DOMException error. Synchronous stat operations on the file when the Blob is created, and before each read in order to detect whether the file data has been modified on disk.
import { openAsBlob } from 'node:fs';
const blob = await openAsBlob('the.file.txt');
const ab = await blob.arrayBuffer();
blob.stream();
@since v19.8.0
static member opendirSync (path: PathLike, ?options: OpenDirOptions) : Dir
static member opendirSync (path: PathLike, ?options: OpenDirOptions) : DirSynchronously open a directory. See opendir(3).
Creates an fs.Dir, which contains all further functions for reading from and cleaning up the directory.
The encoding option sets the encoding for the path while opening the directory and subsequent read operations.
@since v12.12.0
static member readFileSync (path: PathOrFileDescriptor, ?options: U2<string,Options3>) : U2<string,NonSharedBuffer>
static member readFileSync (path: PathOrFileDescriptor, ?options: U2<string,Options3>) : U2<string,NonSharedBuffer>Returns the contents of the path.
For detailed information, see the documentation of the asynchronous version of this API: readFile.
If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
Similar to readFile, when the path is a directory, the behavior of fs.readFileSync() is platform-specific.
import { readFileSync } from 'node:fs';
// macOS, Linux, and Windows
readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
// FreeBSD
readFileSync('<directory>'); // => <data>
Synchronously reads the entire contents of a file.
| Parameter | |
|---|---|
path | filename or file descriptor |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
options | Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'. |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
options | Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'. |
static member readFileSync (path: PathOrFileDescriptor, options: U2<string,Options2>) : string
static member readFileSync (path: PathOrFileDescriptor, options: U2<string,Options2>) : stringReturns the contents of the path.
For detailed information, see the documentation of the asynchronous version of this API: readFile.
If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
Similar to readFile, when the path is a directory, the behavior of fs.readFileSync() is platform-specific.
import { readFileSync } from 'node:fs';
// macOS, Linux, and Windows
readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
// FreeBSD
readFileSync('<directory>'); // => <data>
Synchronously reads the entire contents of a file.
| Parameter | |
|---|---|
path | filename or file descriptor |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
options | Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'. |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
options | Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'. |
static member readFileSync (path: PathOrFileDescriptor, ?options: Options) : NonSharedBuffer
static member readFileSync (path: PathOrFileDescriptor, ?options: Options) : NonSharedBufferReturns the contents of the path.
For detailed information, see the documentation of the asynchronous version of this API: readFile.
If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
Similar to readFile, when the path is a directory, the behavior of fs.readFileSync() is platform-specific.
import { readFileSync } from 'node:fs';
// macOS, Linux, and Windows
readFileSync('<directory>');
// => [Error: EISDIR: illegal operation on a directory, read <directory>]
// FreeBSD
readFileSync('<directory>'); // => <data>
Synchronously reads the entire contents of a file.
@since v0.1.8
| Parameter | |
|---|---|
path | filename or file descriptor |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
options | Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'. |
path | A path to a file. If a URL is provided, it must use the file: protocol. If a file descriptor is provided, the underlying file will not be closed automatically. |
options | Either the encoding for the result, or an object that contains the encoding and an optional flag. If a flag is not provided, it defaults to 'r'. |
static member readSync (fd: float, buffer: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?opts: ReadOptions) : float
static member readSync (fd: float, buffer: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?opts: ReadOptions) : floatReturns the number of bytesRead.
For detailed information, see the documentation of the asynchronous version of this API: read. Similar to the above fs.readSync function, this version takes an optional options object. If no options object is specified, it will default with the above values.
static member readSync (fd: float, buffer: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, offset: float, length: float, ?position: ReadPosition) : float
static member readSync (fd: float, buffer: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, offset: float, length: float, ?position: ReadPosition) : floatReturns the number of bytesRead.
For detailed information, see the documentation of the asynchronous version of this API: read. Similar to the above fs.readSync function, this version takes an optional options object. If no options object is specified, it will default with the above values.
@since v0.1.21
static member readdirSync (path: PathLike, options: Options5) : Dirent<NonSharedBuffer> array
static member readdirSync (path: PathLike, options: Options5) : Dirent<NonSharedBuffer> arrayReads the contents of the directory.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames returned. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the result will contain fs.Dirent objects. Synchronous readdir(3) - read a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | If called with withFileTypes: true the result data will be an array of Dirent. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Must include withFileTypes: true and encoding: 'buffer'. |
static member readdirSync (path: PathLike, options: Options4) : Dirent<string> array
static member readdirSync (path: PathLike, options: Options4) : Dirent<string> arrayReads the contents of the directory.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames returned. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the result will contain fs.Dirent objects. Synchronous readdir(3) - read a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | If called with withFileTypes: true the result data will be an array of Dirent. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Must include withFileTypes: true and encoding: 'buffer'. |
static member readdirSync (path: PathLike, ?options: U2<string,Options3>) : U2<string array,NonSharedBuffer array>
static member readdirSync (path: PathLike, ?options: U2<string,Options3>) : U2<string array,NonSharedBuffer array>Reads the contents of the directory.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames returned. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the result will contain fs.Dirent objects. Synchronous readdir(3) - read a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | If called with withFileTypes: true the result data will be an array of Dirent. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Must include withFileTypes: true and encoding: 'buffer'. |
static member readdirSync (path: PathLike, options: U2<string,Options2>) : NonSharedBuffer array
static member readdirSync (path: PathLike, options: U2<string,Options2>) : NonSharedBuffer arrayReads the contents of the directory.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames returned. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the result will contain fs.Dirent objects. Synchronous readdir(3) - read a directory.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | If called with withFileTypes: true the result data will be an array of Dirent. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | Must include withFileTypes: true and encoding: 'buffer'. |
static member readdirSync (path: PathLike, ?options: U2<string,Options>) : string array
static member readdirSync (path: PathLike, ?options: U2<string,Options>) : string arrayReads the contents of the directory.
See the POSIX readdir(3) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the filenames returned. If the encoding is set to 'buffer', the filenames returned will be passed as Buffer objects.
If options.withFileTypes is set to true, the result will contain fs.Dirent objects. Synchronous readdir(3) - read a directory.
@since v0.1.21
static member readlinkSync (path: PathLike, options: BufferEncodingOption) : NonSharedBuffer
static member readlinkSync (path: PathLike, options: BufferEncodingOption) : NonSharedBufferReturns the symbolic link's string value.
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the link path returned. If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object. Synchronous readlink(2) - read value of a symbolic link.
| Parameter | |
|---|---|
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
path | A path to a file. If a URL is provided, it must use the file: protocol. |
options | The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, 'utf8' is used. |
static member readlinkSync (path: PathLike, ?options: EncodingOption) : string
static member readlinkSync (path: PathLike, ?options: EncodingOption) : stringReturns the symbolic link's string value.
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an object with an encoding property specifying the character encoding to use for the link path returned. If the encoding is set to 'buffer', the link path returned will be passed as a Buffer object. Synchronous readlink(2) - read value of a symbolic link.
@since v0.1.31
static member readvSync (fd: float, buffers: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>> array, ?position: float) : float
static member readvSync (fd: float, buffers: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>> array, ?position: float) : floatFor detailed information, see the documentation of the asynchronous version of this API: readv.
@since v13.13.0, v12.17.0
Returns. The number of bytes read.
static member rmdirSync (path: PathLike, ?options: RmDirOptions) : unit
static member rmdirSync (path: PathLike, ?options: RmDirOptions) : unitSynchronous rmdir(2). Returns undefined.
Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error on Windows and an ENOTDIR error on POSIX.
To get a behavior similar to the rm -rf Unix command, use rmSync with options { recursive: true, force: true }.
@since v0.1.21
static member statfsSync (path: PathLike, ?options: StatFsOptions) : U2<BigIntStatsFs,StatsFs>
static member statfsSync (path: PathLike, ?options: StatFsOptions) : U2<BigIntStatsFs,StatsFs>Synchronous statfs(2). Returns information about the mounted file system which contains path.
In case of an error, the err.code will be one of Common System Errors.
@since v19.6.0, v18.15.0
| Parameter | |
|---|---|
path | A path to an existing file or directory on the file system to be queried. |
static member statfsSync (path: PathLike, options: Options2) : BigIntStatsFs
static member statfsSync (path: PathLike, options: Options2) : BigIntStatsFsSynchronous statfs(2). Returns information about the mounted file system which contains path.
In case of an error, the err.code will be one of Common System Errors.
@since v19.6.0, v18.15.0
| Parameter | |
|---|---|
path | A path to an existing file or directory on the file system to be queried. |
static member statfsSync (path: PathLike, ?options: Options) : StatsFs
static member statfsSync (path: PathLike, ?options: Options) : StatsFsSynchronous statfs(2). Returns information about the mounted file system which contains path.
In case of an error, the err.code will be one of Common System Errors.
@since v19.6.0, v18.15.0
| Parameter | |
|---|---|
path | A path to an existing file or directory on the file system to be queried. |
static member truncateSync (path: PathLike, ?len: float) : unit
static member truncateSync (path: PathLike, ?len: float) : unitTruncates the file. Returns undefined. A file descriptor can also be passed as the first argument. In this case, fs.ftruncateSync() is called.
Passing a file descriptor is deprecated and may result in an error being thrown in the future.
@since v0.8.6
static member unwatchFile (filename: PathLike, ?listener: BigIntStatsListener) : unit
static member unwatchFile (filename: PathLike, ?listener: BigIntStatsListener) : unitStop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed, effectively stopping watching of filename.
Calling fs.unwatchFile() with a filename that is not being watched is a no-op, not an error.
Using watch is more efficient than fs.watchFile() and fs.unwatchFile(). fs.watch() should be used instead of fs.watchFile() and fs.unwatchFile() when possible.
@since v0.1.31
| Parameter | |
|---|---|
listener | Optional, a listener previously attached using fs.watchFile() |
static member unwatchFile (filename: PathLike, ?listener: StatsListener) : unit
static member unwatchFile (filename: PathLike, ?listener: StatsListener) : unitStop watching for changes on filename. If listener is specified, only that particular listener is removed. Otherwise, all listeners are removed, effectively stopping watching of filename.
Calling fs.unwatchFile() with a filename that is not being watched is a no-op, not an error.
Using watch is more efficient than fs.watchFile() and fs.unwatchFile(). fs.watch() should be used instead of fs.watchFile() and fs.unwatchFile() when possible.
@since v0.1.31
| Parameter | |
|---|---|
listener | Optional, a listener previously attached using fs.watchFile() |
static member watch (filename: PathLike, listener: Listener) : FSWatcher
static member watch (filename: PathLike, listener: Listener) : FSWatcherWatch for changes on filename, where filename is either a file or a directory.
The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventTypeis either 'rename' or 'change', and filename is the name of the file which triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.
The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of eventType.
If a signal is passed, aborting the corresponding AbortController will close the returned fs.FSWatcher.
@since v0.5.10
static member watch (filename: PathLike, options: U2<string,WatchOptions> option, listener: Listener3) : FSWatcher
static member watch (filename: PathLike, options: U2<string,WatchOptions> option, listener: Listener3) : FSWatcherWatch for changes on filename, where filename is either a file or a directory.
The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventTypeis either 'rename' or 'change', and filename is the name of the file which triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.
The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of eventType.
If a signal is passed, aborting the corresponding AbortController will close the returned fs.FSWatcher.
@since v0.5.10
static member watch (filename: PathLike, options: U2<string,WatchOptionsWithBufferEncoding>, listener: Listener2) : FSWatcher
static member watch (filename: PathLike, options: U2<string,WatchOptionsWithBufferEncoding>, listener: Listener2) : FSWatcherWatch for changes on filename, where filename is either a file or a directory.
The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventTypeis either 'rename' or 'change', and filename is the name of the file which triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.
The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of eventType.
If a signal is passed, aborting the corresponding AbortController will close the returned fs.FSWatcher.
@since v0.5.10
static member watch (filename: PathLike, ?options: U2<string,WatchOptionsWithStringEncoding>, ?listener: Listener) : FSWatcher
static member watch (filename: PathLike, ?options: U2<string,WatchOptionsWithStringEncoding>, ?listener: Listener) : FSWatcherWatch for changes on filename, where filename is either a file or a directory.
The second argument is optional. If options is provided as a string, it specifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventTypeis either 'rename' or 'change', and filename is the name of the file which triggered the event.
On most platforms, 'rename' is emitted whenever a filename appears or disappears in the directory.
The listener callback is attached to the 'change' event fired by fs.FSWatcher, but it is not the same thing as the 'change' value of eventType.
If a signal is passed, aborting the corresponding AbortController will close the returned fs.FSWatcher.
@since v0.5.10
static member watchFile (filename: PathLike, listener: StatsListener) : StatWatcher
static member watchFile (filename: PathLike, listener: StatsListener) : StatWatcherWatch for changes on filename. The callback listener will be called each time the file is accessed.
The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.
The listener gets two arguments the current stat object and the previous stat object:
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
These stat objects are instances of fs.Stat. If the bigint option is true, the numeric values in these objects are specified as BigInts.
To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtimeMs and prev.mtimeMs.
When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.
Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.
When a file being watched by fs.watchFile() disappears and reappears, then the contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).
This happens when:
- the file is deleted, followed by a restore
- the file is renamed and then renamed a second time back to its original name Watch for changes on
filename. The callbacklistenerwill be called each time the file is accessed.
| Parameter | |
|---|---|
filename | A path to a file or directory. If a URL is provided, it must use the file: protocol. |
static member watchFile (filename: PathLike, options: Options2 option, listener: BigIntStatsListener) : StatWatcher
static member watchFile (filename: PathLike, options: Options2 option, listener: BigIntStatsListener) : StatWatcherWatch for changes on filename. The callback listener will be called each time the file is accessed.
The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.
The listener gets two arguments the current stat object and the previous stat object:
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
These stat objects are instances of fs.Stat. If the bigint option is true, the numeric values in these objects are specified as BigInts.
To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtimeMs and prev.mtimeMs.
When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.
Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.
When a file being watched by fs.watchFile() disappears and reappears, then the contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).
This happens when:
- the file is deleted, followed by a restore
- the file is renamed and then renamed a second time back to its original name Watch for changes on
filename. The callbacklistenerwill be called each time the file is accessed.
@since v0.1.31
| Parameter | |
|---|---|
filename | A path to a file or directory. If a URL is provided, it must use the file: protocol. |
static member watchFile (filename: PathLike, options: Options option, listener: StatsListener) : StatWatcher
static member watchFile (filename: PathLike, options: Options option, listener: StatsListener) : StatWatcherWatch for changes on filename. The callback listener will be called each time the file is accessed.
The options argument may be omitted. If provided, it should be an object. The options object may contain a boolean named persistent that indicates whether the process should continue to run as long as files are being watched. The options object may specify an interval property indicating how often the target should be polled in milliseconds.
The listener gets two arguments the current stat object and the previous stat object:
import { watchFile } from 'node:fs';
watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
These stat objects are instances of fs.Stat. If the bigint option is true, the numeric values in these objects are specified as BigInts.
To be notified when the file was modified, not just accessed, it is necessary to compare curr.mtimeMs and prev.mtimeMs.
When an fs.watchFile operation results in an ENOENT error, it will invoke the listener once, with all the fields zeroed (or, for dates, the Unix Epoch). If the file is created later on, the listener will be called again, with the latest stat objects. This is a change in functionality since v0.10.
Using watch is more efficient than fs.watchFile and fs.unwatchFile. fs.watch should be used instead of fs.watchFile and fs.unwatchFile when possible.
When a file being watched by fs.watchFile() disappears and reappears, then the contents of previous in the second callback event (the file's reappearance) will be the same as the contents of previous in the first callback event (its disappearance).
This happens when:
- the file is deleted, followed by a restore
- the file is renamed and then renamed a second time back to its original name Watch for changes on
filename. The callbacklistenerwill be called each time the file is accessed.
@since v0.1.31
static member writeFileSync (file: PathOrFileDescriptor, data: BinaryLike, ?options: U2<string,WriteFileOptions2>) : unit
static member writeFileSync (file: PathOrFileDescriptor, data: BinaryLike, ?options: U2<string,WriteFileOptions2>) : unitReturns undefined.
The mode option only affects the newly created file. See open for more details.
For detailed information, see the documentation of the asynchronous version of this API: writeFile.
@since v0.1.29
| Parameter | |
|---|---|
file | filename or file descriptor |
static member writeSync (fd: float, string: string, ?position: float, ?encoding: BufferEncoding) : float
static member writeSync (fd: float, string: string, ?position: float, ?encoding: BufferEncoding) : floatFor detailed information, see the documentation of the asynchronous version of this API: write. Synchronously writes string to the file referenced by the supplied file descriptor, returning the number of bytes written.
| Parameter | |
|---|---|
fd | A file descriptor. |
string | A string to write. |
position | The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. |
encoding | The expected string encoding. |
static member writeSync (fd: float, buffer: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?offset: float, ?length: float, ?position: float) : float
static member writeSync (fd: float, buffer: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>>, ?offset: float, ?length: float, ?position: float) : floatFor detailed information, see the documentation of the asynchronous version of this API: write. Synchronously writes string to the file referenced by the supplied file descriptor, returning the number of bytes written.
@since v0.1.21
| Parameter | |
|---|---|
fd | A file descriptor. |
string | A string to write. |
position | The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. |
encoding | The expected string encoding. |
Returns. The number of bytes written.
static member writevSync (fd: float, buffers: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>> array, ?position: float) : float
static member writevSync (fd: float, buffers: U12<BigInt64Array<U2<ArrayBuffer,SharedArrayBuffer>>,BigUint64Array<U2<ArrayBuffer,SharedArrayBuffer>>,DataView<U2<ArrayBuffer,SharedArrayBuffer>>,Float32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Float64Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Int8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint16Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint32Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8Array<U2<ArrayBuffer,SharedArrayBuffer>>,Uint8ClampedArray<U2<ArrayBuffer,SharedArrayBuffer>>> array, ?position: float) : floatFor detailed information, see the documentation of the asynchronous version of this API: writev.
@since v12.9.0
Returns. The number of bytes written.