Synchronous API
History
The synchronous APIs perform all operations synchronously, blocking the event loop until the operation completes or fails.
fs.accessSync
History
path parameter can be a WHATWG URL object using file: protocol.fs.accessSync(path, mode?): void
Synchronously tests a user's permissions for the file or directory specified
by path. The mode argument is an optional integer that specifies the
accessibility checks to be performed. 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!'); }
fs.appendFileSync(path, data, options?): void
Synchronously 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 fs.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); }
fs.chmodSync
History
path parameter can be a WHATWG URL object using file: protocol.fs.chmodSync(path, mode): void
For detailed information, see the documentation of the asynchronous version of
this API: fs.chmod().
See the POSIX chmod(2) documentation for more detail.
fs.chownSync
History
path parameter can be a WHATWG URL object using file: protocol.fs.chownSync(path, uid, gid): void
Synchronously changes owner and group of a file. Returns undefined.
This is the synchronous version of fs.chown().
See the POSIX chown(2) documentation for more detail.
fs.closeSync(fd): void
integerCloses 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.
fs.copyFileSync
History
flags argument to mode and imposed stricter type validation.fs.copyFileSync(src, dest, mode?): void
Synchronously 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.
Symbolic links are followed. If src is a symbolic link, the target file is
copied. If dest is a symbolic link, the target file is overwritten unless
mode contains fs.constants.COPYFILE_EXCL.
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);
fs.cpSync
History
mode option to specify the copy behavior as the mode argument of fs.copyFile().verbatimSymlinks option to specify whether to perform path resolution for symlinks.fs.cpSync(src, dest, options?): void
Objectbooleanfalse.booleanforce is false, and the destination
exists, throw an error. Default: false.Functiontrue to copy the item, false to ignore it. When ignoring a directory,
all of its contents will be skipped as well. Default: undefinedbooleanerrorOnExist option to change this behavior.
Default: true.integerbooleantrue timestamps from src will
be preserved. Default: false.booleanfalsebooleantrue, path resolution for symlinks will
be skipped. Default: falseSynchronously 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/.
fs.existsSync
History
path parameter can be a WHATWG URL object using file: protocol.fs.existsSync(path): boolean
Returns true if the path exists, false otherwise.
For detailed information, see the documentation of the asynchronous version of
this API: fs.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.');
fs.fchmodSync(fd, mode): void
Sets the permissions on the file. Returns undefined.
See the POSIX fchmod(2) documentation for more detail.
fs.fchownSync(fd, uid, gid): void
Sets the owner of the file. Returns undefined.
See the POSIX fchown(2) documentation for more detail.
fs.fdatasyncSync(fd): void
integerForces 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.
fs.fstatSync(fd, options?): fs.Stats
Retrieves the fs.Stats for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
fs.fsyncSync(fd): void
integerRequest 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.
fs.ftruncateSync(fd, len?): void
Truncates the file descriptor. Returns undefined.
For detailed information, see the documentation of the asynchronous version of
this API: fs.ftruncate().
fs.futimesSync
History
NaN, and Infinity are now allowed time specifiers.fs.futimesSync(fd, atime, mtime): void
Synchronous version of fs.futimes(). Returns undefined.
fs.globSync(pattern, options?): string[]
Objecttrue to exclude the item, false to include it. Default: undefined.booleantrue, symbolic links to directories are
followed while expanding ** patterns. Default: false.booleantrue if the glob should return paths as Dirents,
false otherwise. Default: false.string[]When followSymlinks is enabled, detected symbolic link cycles are not
traversed recursively.
import { globSync } from 'node:fs'; console.log(globSync('**/*.js'));
const { globSync } = require('node:fs'); console.log(globSync('**/*.js'));
fs.lchmodSync(path, mode): void
Changes the permissions on a symbolic link. Returns undefined.
This method is only implemented on macOS.
See the POSIX lchmod(2) documentation for more detail.
fs.lchownSync(path, uid, gid): void
Set the owner for the path. Returns undefined.
See the POSIX lchown(2) documentation for more details.
fs.lutimesSync(path, atime, mtime): void
Change 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 fs.lutimes().
fs.linkSync(existingPath, newPath): void
Creates a new link from the existingPath to the newPath. See the POSIX
link(2) documentation for more detail. Returns undefined.
fs.lstatSync
History
throwIfNoEntry option to specify whether an exception should be thrown if the entry does not exist.options object to specify whether the numeric values returned should be bigint.path parameter can be a WHATWG URL object using file: protocol.fs.lstatSync(path, options?): fs.Stats
Retrieves the fs.Stats for the symbolic link referred to by path.
See the POSIX lstat(2) documentation for more details.
fs.mkdirSync(path, options?): string | undefined
Synchronously creates a directory. Returns undefined, or if recursive is
true, the first directory path created.
This is the synchronous version of fs.mkdir().
See the POSIX mkdir(2) documentation for more details.
fs.mkdtempSync(prefix, options?): string
Returns the created directory path.
For detailed information, see the documentation of the asynchronous version of
this API: fs.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.
fs.mkdtempDisposableSync(prefix, options?): Object
Returns a disposable object whose path property holds the created directory
path. When the object is disposed, the directory and its contents will be
removed if it still exists. If the directory cannot be deleted, disposal will
throw an error. The object has a remove() method which will perform the same
task.
See the MDN documentation on using statements for more information about
explicit resource management.
For detailed information, see the documentation of fs.mkdtemp().
There is no callback-based version of this API because it is designed for use
with the using syntax.
The optional options argument can be a string specifying an encoding, or an
object with an encoding property specifying the character encoding to use.
fs.opendirSync
History
recursive option.bufferSize option was introduced.fs.opendirSync(path, options?): fs.Dir
Synchronously 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.
fs.openSync(path, flags?, mode?): number
Returns an integer representing the file descriptor.
For detailed information, see the documentation of the asynchronous version of
this API: fs.open().
fs.readdirSync(path, options?): string[] | Buffer[] | fs.Dirent[]
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.
fs.readFileSync(path, options?): string | Buffer
stringflags. Default: 'r'.Buffer | TypedArray | DataView | FunctionReturns the contents of the path.
For detailed information, see the documentation of the asynchronous version of
this API: fs.readFile().
If the encoding option is specified then this function returns a
string. Otherwise it returns a buffer.
If buffer is provided and no encoding is specified, the returned Buffer is
a view over the supplied buffer containing only the bytes read. If the
supplied buffer is too small to contain the entire file, an error will be
thrown.
Similar to fs.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>
fs.readlinkSync
History
path parameter can be a WHATWG URL object using file: protocol.fs.readlinkSync(path, options?): string | Buffer
Returns 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.
fs.readSync(fd, buffer, offset, length, position?): number
Returns the number of bytesRead.
For detailed information, see the documentation of the asynchronous version of
this API: fs.read().
fs.readSync
History
fs.readSync(fd, buffer, options?): number
Returns the number of bytesRead.
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.
For detailed information, see the documentation of the asynchronous version of
this API: fs.read().
fs.readvSync(fd, buffers, position?): number
For detailed information, see the documentation of the asynchronous version of
this API: fs.readv().
fs.realpathSync(path, options?): string | Buffer
Returns the resolved pathname.
For detailed information, see the documentation of the asynchronous version of
this API: fs.realpath().
fs.realpathSync.native(path, options?): string | Buffer
Synchronous realpath(3).
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 returned. If the encoding is set to 'buffer',
the path returned will be passed as a Buffer object.
On Linux, when Node.js is linked against musl libc, the procfs file system must
be mounted on /proc in order for this function to work. Glibc does not have
this restriction.
fs.renameSync(oldPath, newPath): void
Renames the file from oldPath to newPath. Returns undefined.
See the POSIX rename(2) documentation for more details.
fs.rmdirSync
History
recursive option.fs.rmdirSync(path, { recursive: true }) on a path that is a file is no longer permitted and results in an ENOENT error on Windows and an ENOTDIR error on POSIX.fs.rmdirSync(path, { recursive: true }) on a path that does not exist is no longer permitted and results in a ENOENT error.recursive option is deprecated, using it triggers a deprecation warning.recursive option is deprecated, use fs.rmSync instead.maxBusyTries option is renamed to maxRetries, and its default is 0. The emfileWait option has been removed, and EMFILE errors use the same retry logic as other errors. The retryDelay option is now supported. ENFILE errors are now retried.recursive, maxBusyTries, and emfileWait options are now supported.path parameters can be a WHATWG URL object using file: protocol.fs.rmdirSync(path, options?): void
Synchronous 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 fs.rmSync()
with options { recursive: true, force: true }.
fs.rmSync
History
path parameter can be a WHATWG URL object using file: protocol.fs.rmSync(path, options?): void
Objectbooleantrue, exceptions will be ignored if path does
not exist. Default: false.integerEBUSY, EMFILE, ENFILE, ENOTEMPTY, or
EPERM error is encountered, Node.js will retry the operation with a linear
backoff wait of retryDelay milliseconds longer on each try. This option
represents the number of retries. This option is ignored if the recursive
option is not true. Default: 0.booleantrue, perform a recursive directory removal. In
recursive mode operations are retried on failure. Default: false.integerrecursive option is not true.
Default: 100.Synchronously removes files and directories (modeled on the standard POSIX rm
utility). Returns undefined.
fs.statSync
History
throwIfNoEntry option to specify whether an exception should be thrown if the entry does not exist.options object to specify whether the numeric values returned should be bigint.path parameter can be a WHATWG URL object using file: protocol.fs.statSync(path, options?): fs.Stats
Retrieves the fs.Stats for the path.
fs.statfsSync(path, options?): fs.StatFs
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.
fs.symlinkSync(target, path, type?): void
For detailed information, see the documentation of the asynchronous version of
this API: fs.symlink().
fs.truncateSync(path, len?): void
Truncates 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.
fs.unlinkSync
History
path parameter can be a WHATWG URL object using file: protocol.fs.unlinkSync(path): void
Synchronous unlink(2). Returns undefined.
fs.utimesSync(path, atime, mtime): void
For detailed information, see the documentation of the asynchronous version of
this API: fs.utimes().
fs.writeFileSync
History
flush option is now supported.data parameter an object with an own toString function is no longer supported.data parameter an object with an own toString function is deprecated.data parameter will stringify an object with an explicit toString function.data parameter won't coerce unsupported input to strings anymore.data parameter can now be any TypedArray or a DataView.data parameter can now be a Uint8Array.file parameter can be a file descriptor now.fs.writeFileSync(file, data, options?): void
The mode option only affects the newly created file. See fs.open()
for more details.
For detailed information, see the documentation of the asynchronous version of
this API: fs.writeFile().
fs.writeSync(fd, buffer, offset?, length?, position?): number
For detailed information, see the documentation of the asynchronous version of
this API: fs.write(fd, buffer...).
fs.writeSync(fd, buffer, options?): number
For detailed information, see the documentation of the asynchronous version of
this API: fs.write(fd, buffer...).
fs.writeSync(fd, string, position?, encoding?): number
For detailed information, see the documentation of the asynchronous version of
this API: fs.write(fd, string...).
fs.writevSync(fd, buffers, position?): number
For detailed information, see the documentation of the asynchronous version of
this API: fs.writev().