File system#

Stability: 2 - Stable

Source Code:lib/fs.js

Thenode:fs module enables interacting with the file system in away modeled on standard POSIX functions.

To use the promise-based APIs:

import *as fsfrom'node:fs/promises';const fs =require('node:fs/promises');

To use the callback and sync APIs:

import *as fsfrom'node:fs';const fs =require('node:fs');

All file system operations have synchronous, callback, and promise-basedforms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).

Promise example#

Promise-based operations return a promise that is fulfilled when theasynchronous operation is complete.

import { unlink }from'node:fs/promises';try {awaitunlink('/tmp/hello');console.log('successfully deleted /tmp/hello');}catch (error) {console.error('there was an error:', error.message);}const { unlink } =require('node:fs/promises');(asyncfunction(path) {try {awaitunlink(path);console.log(`successfully deleted${path}`);  }catch (error) {console.error('there was an error:', error.message);  }})('/tmp/hello');

Callback example#

The callback form takes a completion callback function as its lastargument and invokes the operation asynchronously. The arguments passed tothe completion callback depend on the method, but the first argument is alwaysreserved for an exception. If the operation is completed successfully, thenthe first argument isnull orundefined.

import { unlink }from'node:fs';unlink('/tmp/hello',(err) => {if (err)throw err;console.log('successfully deleted /tmp/hello');});const { unlink } =require('node:fs');unlink('/tmp/hello',(err) => {if (err)throw err;console.log('successfully deleted /tmp/hello');});

The callback-based versions of thenode:fs module APIs are preferable overthe use of the promise APIs when maximal performance (both in terms ofexecution time and memory allocation) is required.

Synchronous example#

The synchronous APIs block the Node.js event loop and further JavaScriptexecution until the operation is complete. Exceptions are thrown immediatelyand can be handled usingtry…catch, or can be allowed to bubble up.

import { unlinkSync }from'node:fs';try {unlinkSync('/tmp/hello');console.log('successfully deleted /tmp/hello');}catch (err) {// handle the error}const { unlinkSync } =require('node:fs');try {unlinkSync('/tmp/hello');console.log('successfully deleted /tmp/hello');}catch (err) {// handle the error}

Promises API#

History
VersionChanges
v14.0.0

Exposed asrequire('fs/promises').

v11.14.0, v10.17.0

This API is no longer experimental.

v10.1.0

The API is accessible viarequire('fs').promises only.

v10.0.0

Added in: v10.0.0

Thefs/promises API provides asynchronous file system methods that returnpromises.

The promise APIs use the underlying Node.js threadpool to perform filesystem operations off the event loop thread. These operations are notsynchronized or threadsafe. Care must be taken when performing multipleconcurrent modifications on the same file or data corruption may occur.

Class:FileHandle#

Added in: v10.0.0

A<FileHandle> object is an object wrapper for a numeric file descriptor.

Instances of the<FileHandle> object are created by thefsPromises.open()method.

All<FileHandle> objects are<EventEmitter>s.

If a<FileHandle> is not closed using thefilehandle.close() method, it willtry to automatically close the file descriptor and emit a process warning,helping to prevent memory leaks. Please do not rely on this behavior becauseit can be unreliable and the file may not be closed. Instead, always explicitlyclose<FileHandle>s. Node.js may change this behavior in the future.

Event:'close'#
Added in: v15.4.0

The'close' event is emitted when the<FileHandle> has been closed and can nolonger be used.

filehandle.appendFile(data[, options])#
History
VersionChanges
v21.1.0, v20.10.0

Theflush option is now supported.

v15.14.0, v14.18.0

Thedata argument supportsAsyncIterable,Iterable, andStream.

v14.0.0

Thedata parameter won't coerce unsupported input to strings anymore.

v10.0.0

Added in: v10.0.0

Alias offilehandle.writeFile().

When operating on file handles, the mode cannot be changed from what it was setto withfsPromises.open(). Therefore, this is equivalent tofilehandle.writeFile().

filehandle.chmod(mode)#
Added in: v10.0.0
  • mode<integer> the file mode bit mask.
  • Returns:<Promise> Fulfills withundefined upon success.

Modifies the permissions on the file. Seechmod(2).

filehandle.chown(uid, gid)#
Added in: v10.0.0
  • uid<integer> The file's new owner's user id.
  • gid<integer> The file's new group's group id.
  • Returns:<Promise> Fulfills withundefined upon success.

Changes the ownership of the file. A wrapper forchown(2).

filehandle.close()#
Added in: v10.0.0
  • Returns:<Promise> Fulfills withundefined upon success.

Closes the file handle after waiting for any pending operation on the handle tocomplete.

import { open }from'node:fs/promises';let filehandle;try {  filehandle =awaitopen('thefile.txt','r');}finally {await filehandle?.close();}
filehandle.createReadStream([options])#
Added in: v16.11.0

options can includestart andend values to read a range of bytes fromthe file instead of the entire file. Bothstart andend are inclusive andstart counting at 0, allowed values are in the[0,Number.MAX_SAFE_INTEGER] range. Ifstart isomitted orundefined,filehandle.createReadStream() reads sequentially fromthe current file position. Theencoding can be any one of those accepted by<Buffer>.

If theFileHandle points to a character device that only supports blockingreads (such as keyboard or sound card), read operations do not finish until datais available. This can prevent the process from exiting and the stream fromclosing naturally.

By default, the stream will emit a'close' event after it has beendestroyed. Set theemitClose option tofalse to change this behavior.

import { open }from'node:fs/promises';const fd =awaitopen('/dev/input/event0');// Create a stream from some character device.const stream = fd.createReadStream();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);

IfautoClose is false, then the file descriptor won't be closed, even ifthere's an error. It is the application's responsibility to close it and makesure there's no file descriptor leak. IfautoClose is set to true (defaultbehavior), on'error' or'end' the file descriptor will be closedautomatically.

An example to read the last 10 bytes of a file which is 100 bytes long:

import { open }from'node:fs/promises';const fd =awaitopen('sample.txt');fd.createReadStream({start:90,end:99 });
filehandle.createWriteStream([options])#
History
VersionChanges
v21.0.0, v20.10.0

Theflush option is now supported.

v16.11.0

Added in: v16.11.0

options may also include astart option to allow writing data at someposition past the beginning of the file, allowed values are in the[0,Number.MAX_SAFE_INTEGER] range. Modifying a file rather thanreplacing it may require theflagsopen option to be set tor+ rather thanthe defaultr. Theencoding can be any one of those accepted by<Buffer>.

IfautoClose is set to true (default behavior) on'error' or'finish'the file descriptor will be closed automatically. IfautoClose 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 nofile descriptor leak.

By default, the stream will emit a'close' event after it has beendestroyed. Set theemitClose option tofalse to change this behavior.

filehandle.datasync()#
Added in: v10.0.0
  • Returns:<Promise> Fulfills withundefined upon success.

Forces all currently queued I/O operations associated with the file to theoperating system's synchronized I/O completion state. Refer to the POSIXfdatasync(2) documentation for details.

Unlikefilehandle.sync this method does not flush modified metadata.

filehandle.fd#
Added in: v10.0.0
filehandle.read(buffer, offset, length, position)#
History
VersionChanges
v21.0.0

Accepts bigint values asposition.

v10.0.0

Added in: v10.0.0

  • buffer<Buffer> |<TypedArray> |<DataView> A buffer that will be filled with thefile data read.
  • offset<integer> The location in the buffer at which to start filling.Default:0
  • length<integer> The number of bytes to read.Default:buffer.byteLength - offset
  • position<integer> |<bigint> |<null> The location where to begin reading datafrom the file. Ifnull or-1, data will be read from the current fileposition, and the position will be updated. Ifposition is a non-negativeinteger, the current file position will remain unchanged.Default:null
  • Returns:<Promise> Fulfills upon success with an object with two properties:

Reads data from the file and stores that in the given buffer.

If the file is not modified concurrently, the end-of-file is reached when thenumber of bytes read is zero.

filehandle.read([options])#
History
VersionChanges
v21.0.0

Accepts bigint values asposition.

v13.11.0, v12.17.0

Added in: v13.11.0, v12.17.0

  • options<Object>
    • buffer<Buffer> |<TypedArray> |<DataView> A buffer that will be filled with thefile data read.Default:Buffer.alloc(16384)
    • offset<integer> The location in the buffer at which to start filling.Default:0
    • length<integer> The number of bytes to read.Default:buffer.byteLength - offset
    • position<integer> |<bigint> |<null> The location where to begin reading datafrom the file. Ifnull or-1, data will be read from the current fileposition, and the position will be updated. Ifposition is a non-negativeinteger, the current file position will remain unchanged.Default::null
  • Returns:<Promise> Fulfills upon success with an object with two properties:

Reads data from the file and stores that in the given buffer.

If the file is not modified concurrently, the end-of-file is reached when thenumber of bytes read is zero.

filehandle.read(buffer[, options])#
History
VersionChanges
v21.0.0

Accepts bigint values asposition.

v18.2.0, v16.17.0

Added in: v18.2.0, v16.17.0

  • buffer<Buffer> |<TypedArray> |<DataView> A buffer that will be filled with thefile data read.
  • options<Object>
    • offset<integer> The location in the buffer at which to start filling.Default:0
    • length<integer> The number of bytes to read.Default:buffer.byteLength - offset
    • position<integer> |<bigint> |<null> The location where to begin reading datafrom the file. Ifnull or-1, data will be read from the current fileposition, and the position will be updated. Ifposition is a non-negativeinteger, the current file position will remain unchanged.Default::null
  • Returns:<Promise> Fulfills upon success with an object with two properties:

Reads data from the file and stores that in the given buffer.

If the file is not modified concurrently, the end-of-file is reached when thenumber of bytes read is zero.

filehandle.readableWebStream([options])#
History
VersionChanges
v24.2.0

Added theautoClose option.

v24.0.0

Marking the API stable.

v23.8.0, v22.15.0

Removed option to create a 'bytes' stream. Streams are now always 'bytes' streams.

v20.0.0, v18.17.0

Added option to create a 'bytes' stream.

v17.0.0

Added in: v17.0.0

Returns a byte-orientedReadableStream that may be used to read the file'scontents.

An error will be thrown if this method is called more than once or is calledafter theFileHandle is closed or closing.

import {  open,}from'node:fs/promises';const file =awaitopen('./some/file/to/read');forawait (const chunkof file.readableWebStream())console.log(chunk);await file.close();const {  open,} =require('node:fs/promises');(async () => {const file =awaitopen('./some/file/to/read');forawait (const chunkof file.readableWebStream())console.log(chunk);await file.close();})();

While theReadableStream will read the file to completion, it will notclose theFileHandle automatically. User code must still call thefileHandle.close() method.

filehandle.readFile(options)#
Added in: v10.0.0
  • options<Object> |<string>
  • Returns:<Promise> Fulfills upon a successful read with the contents of thefile. If no encoding is specified (usingoptions.encoding), the data isreturned as a<Buffer> object. Otherwise, the data will be a string.

Asynchronously reads the entire contents of a file.

Ifoptions is a string, then it specifies theencoding.

The<FileHandle> has to support reading.

If one or morefilehandle.read() calls are made on a file handle and then afilehandle.readFile() call is made, the data will be read from the currentposition till the end of the file. It doesn't always read from the beginningof the file.

filehandle.readLines([options])#
Added in: v18.11.0

Convenience method to create areadline interface and stream over the file.Seefilehandle.createReadStream() for the options.

import { open }from'node:fs/promises';const file =awaitopen('./some/file/to/read');forawait (const lineof file.readLines()) {console.log(line);}const { open } =require('node:fs/promises');(async () => {const file =awaitopen('./some/file/to/read');forawait (const lineof file.readLines()) {console.log(line);  }})();
filehandle.readv(buffers[, position])#
Added in: v13.13.0, v12.17.0

Read from a file and write to an array of<ArrayBufferView>s

filehandle.stat([options])#
History
VersionChanges
v10.5.0

Accepts an additionaloptions object to specify whether the numeric values returned should be bigint.

v10.0.0

Added in: v10.0.0

filehandle.sync()#
Added in: v10.0.0
  • Returns:<Promise> Fulfills withundefined upon success.

Request that all data for the open file descriptor is flushed to the storagedevice. The specific implementation is operating system and device specific.Refer to the POSIXfsync(2) documentation for more detail.

filehandle.truncate(len)#
Added in: v10.0.0

Truncates the file.

If the file was larger thanlen bytes, only the firstlen bytes will beretained in the file.

The following example retains only the first four bytes of the file:

import { open }from'node:fs/promises';let filehandle =null;try {  filehandle =awaitopen('temp.txt','r+');await filehandle.truncate(4);}finally {await filehandle?.close();}

If the file previously was shorter thanlen bytes, it is extended, and theextended part is filled with null bytes ('\0'):

Iflen is negative then0 will be used.

filehandle.utimes(atime, mtime)#
Added in: v10.0.0

Change the file system timestamps of the object referenced by the<FileHandle>then fulfills the promise with no arguments upon success.

filehandle.write(buffer, offset[, length[, position]])#
History
VersionChanges
v14.0.0

Thebuffer parameter won't coerce unsupported input to buffers anymore.

v10.0.0

Added in: v10.0.0

  • buffer<Buffer> |<TypedArray> |<DataView>
  • offset<integer> The start position from withinbuffer where the datato write begins.
  • length<integer> The number of bytes frombuffer to write.Default:buffer.byteLength - offset
  • position<integer> |<null> The offset from the beginning of the file where thedata frombuffer should be written. Ifposition is not anumber,the data will be written at the current position. See the POSIXpwrite(2)documentation for more detail.Default:null
  • Returns:<Promise>

Writebuffer to the file.

The promise is fulfilled with an object containing two properties:

It is unsafe to usefilehandle.write() multiple times on the same filewithout waiting for the promise to be fulfilled (or rejected). For thisscenario, usefilehandle.createWriteStream().

On Linux, positional writes do not work when the file is opened in append mode.The kernel ignores the position argument and always appends the data tothe end of the file.

filehandle.write(buffer[, options])#
Added in: v18.3.0, v16.17.0

Writebuffer to the file.

Similar to the abovefilehandle.write function, this version takes anoptionaloptions object. If nooptions object is specified, it willdefault with the above values.

filehandle.write(string[, position[, encoding]])#
History
VersionChanges
v14.0.0

Thestring parameter won't coerce unsupported input to strings anymore.

v10.0.0

Added in: v10.0.0

  • string<string>
  • position<integer> |<null> The offset from the beginning of the file where thedata fromstring should be written. Ifposition is not anumber thedata will be written at the current position. See the POSIXpwrite(2)documentation for more detail.Default:null
  • encoding<string> The expected string encoding.Default:'utf8'
  • Returns:<Promise>

Writestring to the file. Ifstring is not a string, the promise isrejected with an error.

The promise is fulfilled with an object containing two properties:

  • bytesWritten<integer> the number of bytes written
  • buffer<string> a reference to thestring written.

It is unsafe to usefilehandle.write() multiple times on the same filewithout waiting for the promise to be fulfilled (or rejected). For thisscenario, usefilehandle.createWriteStream().

On Linux, positional writes do not work when the file is opened in append mode.The kernel ignores the position argument and always appends the data tothe end of the file.

filehandle.writeFile(data, options)#
History
VersionChanges
v15.14.0, v14.18.0

Thedata argument supportsAsyncIterable,Iterable, andStream.

v14.0.0

Thedata parameter won't coerce unsupported input to strings anymore.

v10.0.0

Added in: v10.0.0

Asynchronously writes data to a file, replacing the file if it already exists.data can be a string, a buffer, an<AsyncIterable>, or an<Iterable> object.The promise is fulfilled with no arguments upon success.

Ifoptions is a string, then it specifies theencoding.

The<FileHandle> has to support writing.

It is unsafe to usefilehandle.writeFile() multiple times on the same filewithout waiting for the promise to be fulfilled (or rejected).

If one or morefilehandle.write() calls are made on a file handle and then afilehandle.writeFile() call is made, the data will be written from thecurrent position till the end of the file. It doesn't always write from thebeginning of the file.

filehandle.writev(buffers[, position])#
Added in: v12.9.0

Write an array of<ArrayBufferView>s to the file.

The promise is fulfilled with an object containing a two properties:

It is unsafe to callwritev() multiple times on the same file without waitingfor the promise to be fulfilled (or rejected).

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 tothe end of the file.

filehandle[Symbol.asyncDispose]()#
History
VersionChanges
v24.2.0

No longer experimental.

v20.4.0, v18.18.0

Added in: v20.4.0, v18.18.0

Callsfilehandle.close() and returns a promise that fulfills when thefilehandle is closed.

fsPromises.access(path[, mode])#

Added in: v10.0.0

Tests a user's permissions for the file or directory specified bypath.Themode argument is an optional integer that specifies the accessibilitychecks to be performed.mode should be either the valuefs.constants.F_OKor a mask consisting of the bitwise OR of any offs.constants.R_OK,fs.constants.W_OK, andfs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). CheckFile access constants forpossible values ofmode.

If the accessibility check is successful, the promise is fulfilled with novalue. If any of the accessibility checks fail, the promise is rejectedwith an<Error> object. The following example checks if the file/etc/passwd can be read and written by the current process.

import { access, constants }from'node:fs/promises';try {awaitaccess('/etc/passwd', constants.R_OK | constants.W_OK);console.log('can access');}catch {console.error('cannot access');}

UsingfsPromises.access() to check for the accessibility of a file beforecallingfsPromises.open() is not recommended. Doing so introduces a racecondition, since other processes may change the file's state between the twocalls. Instead, user code should open/read/write the file directly and handlethe error raised if the file is not accessible.

fsPromises.appendFile(path, data[, options])#

History
VersionChanges
v21.1.0, v20.10.0

Theflush option is now supported.

v10.0.0

Added in: v10.0.0

Asynchronously append data to a file, creating the file if it does not yetexist.data can be a string or a<Buffer>.

Ifoptions is a string, then it specifies theencoding.

Themode option only affects the newly created file. Seefs.open()for more details.

Thepath may be specified as a<FileHandle> that has been openedfor appending (usingfsPromises.open()).

fsPromises.chmod(path, mode)#

Added in: v10.0.0

Changes the permissions of a file.

fsPromises.chown(path, uid, gid)#

Added in: v10.0.0

Changes the ownership of a file.

fsPromises.copyFile(src, dest[, mode])#

History
VersionChanges
v14.0.0

Changedflags argument tomode and imposed stricter type validation.

v10.0.0

Added in: v10.0.0

  • src<string> |<Buffer> |<URL> source filename to copy
  • dest<string> |<Buffer> |<URL> destination filename of the copy operation
  • mode<integer> Optional modifiers that specify the behavior of the copyoperation. It is possible to create a mask consisting of the bitwise OR oftwo or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE)Default:0.
    • fs.constants.COPYFILE_EXCL: The copy operation will fail ifdestalready exists.
    • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to createa 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 tocreate a copy-on-write reflink. If the platform does not supportcopy-on-write, then the operation will fail.
  • Returns:<Promise> Fulfills withundefined upon success.

Asynchronously copiessrc todest. By default,dest is overwritten if italready exists.

No guarantees are made about the atomicity of the copy operation. If anerror occurs after the destination file has been opened for writing, an attemptwill be made to remove the destination.

import { copyFile, constants }from'node:fs/promises';try {awaitcopyFile('source.txt','destination.txt');console.log('source.txt was copied to destination.txt');}catch {console.error('The file could not be copied');}// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.try {awaitcopyFile('source.txt','destination.txt', constants.COPYFILE_EXCL);console.log('source.txt was copied to destination.txt');}catch {console.error('The file could not be copied');}

fsPromises.cp(src, dest[, options])#

History
VersionChanges
v22.3.0

This API is no longer experimental.

v20.1.0, v18.17.0

Accept an additionalmode option to specify the copy behavior as themode argument offs.copyFile().

v17.6.0, v16.15.0

Accepts an additionalverbatimSymlinks option to specify whether to perform path resolution for symlinks.

v16.7.0

Added in: v16.7.0

  • src<string> |<URL> source path to copy.
  • dest<string> |<URL> destination path to copy to.
  • options<Object>
    • dereference<boolean> dereference symlinks.Default:false.
    • errorOnExist<boolean> whenforce isfalse, and the destinationexists, throw an error.Default:false.
    • filter<Function> Function to filter copied files/directories. Returntrue to copy the item,false to ignore it. When ignoring a directory,all of its contents will be skipped as well. Can also return aPromisethat resolves totrue orfalseDefault:undefined.
      • src<string> source path to copy.
      • dest<string> destination path to copy to.
      • Returns:<boolean> |<Promise> A value that is coercible toboolean oraPromise that fulfils with such value.
    • force<boolean> overwrite existing file or directory. The copyoperation will ignore errors if you set this to false and the destinationexists. Use theerrorOnExist option to change this behavior.Default:true.
    • mode<integer> modifiers for copy operation.Default:0.Seemode flag offsPromises.copyFile().
    • preserveTimestamps<boolean> Whentrue timestamps fromsrc willbe preserved.Default:false.
    • recursive<boolean> copy directories recursivelyDefault:false
    • verbatimSymlinks<boolean> Whentrue, path resolution for symlinks willbe skipped.Default:false
  • Returns:<Promise> Fulfills withundefined upon success.

Asynchronously copies the entire directory structure fromsrc todest,including subdirectories and files.

When copying a directory to another directory, globs are not supported andbehavior is similar tocp dir1/ dir2/.

fsPromises.glob(pattern[, options])#

History
VersionChanges
v24.1.0

Add support forURL instances forcwd option.

v24.0.0

Marking the API stable.

v23.7.0, v22.14.0

Add support forexclude option to accept glob patterns.

v22.2.0

Add support forwithFileTypes as an option.

v22.0.0

Added in: v22.0.0

  • pattern<string> |<string[]>
  • options<Object>
    • cwd<string> |<URL> current working directory.Default:process.cwd()
    • exclude<Function> |<string[]> Function to filter out files/directories or alist of glob patterns to be excluded. If a function is provided, returntrue to exclude the item,false to include it.Default:undefined.If a string array is provided, each string should be a glob pattern thatspecifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') arenot supported.
    • withFileTypes<boolean>true if the glob should return paths as Dirents,false otherwise.Default:false.
  • Returns:<AsyncIterator> An AsyncIterator that yields the paths of filesthat match the pattern.
import { glob }from'node:fs/promises';forawait (const entryofglob('**/*.js'))console.log(entry);const { glob } =require('node:fs/promises');(async () => {forawait (const entryofglob('**/*.js'))console.log(entry);})();

fsPromises.lchmod(path, mode)#

Deprecated since: v10.0.0

Stability: 0 - Deprecated

Changes the permissions on a symbolic link.

This method is only implemented on macOS.

fsPromises.lchown(path, uid, gid)#

History
VersionChanges
v10.6.0

This API is no longer deprecated.

v10.0.0

Added in: v10.0.0

Changes the ownership on a symbolic link.

fsPromises.lutimes(path, atime, mtime)#

Added in: v14.5.0, v12.19.0

Changes the access and modification times of a file in the same way asfsPromises.utimes(), with the difference that if the path refers to asymbolic link, then the link is not dereferenced: instead, the timestamps ofthe symbolic link itself are changed.

fsPromises.link(existingPath, newPath)#

Added in: v10.0.0

Creates a new link from theexistingPath to thenewPath. See the POSIXlink(2) documentation for more detail.

fsPromises.lstat(path[, options])#

History
VersionChanges
v10.5.0

Accepts an additionaloptions object to specify whether the numeric values returned should be bigint.

v10.0.0

Added in: v10.0.0

Equivalent tofsPromises.stat() unlesspath refers to a symbolic link,in which case the link itself is stat-ed, not the file that it refers to.Refer to the POSIXlstat(2) document for more detail.

fsPromises.mkdir(path[, options])#

Added in: v10.0.0

Asynchronously creates a directory.

The optionaloptions argument can be an integer specifyingmode (permissionand sticky bits), or an object with amode property and arecursiveproperty indicating whether parent directories should be created. CallingfsPromises.mkdir() whenpath is a directory that exists results in arejection only whenrecursive is false.

import { mkdir }from'node:fs/promises';try {const projectFolder =newURL('./test/project/',import.meta.url);const createDir =awaitmkdir(projectFolder, {recursive:true });console.log(`created${createDir}`);}catch (err) {console.error(err.message);}const { mkdir } =require('node:fs/promises');const { join } =require('node:path');asyncfunctionmakeDirectory() {const projectFolder =join(__dirname,'test','project');const dirCreation =awaitmkdir(projectFolder, {recursive:true });console.log(dirCreation);return dirCreation;}makeDirectory().catch(console.error);

fsPromises.mkdtemp(prefix[, options])#

History
VersionChanges
v20.6.0, v18.19.0

Theprefix parameter now accepts buffers and URL.

v16.5.0, v14.18.0

Theprefix parameter now accepts an empty string.

v10.0.0

Added in: v10.0.0

Creates a unique temporary directory. A unique directory name is generated byappending six random characters to the end of the providedprefix. Due toplatform inconsistencies, avoid trailingX characters inprefix. Someplatforms, notably the BSDs, can return more than six random characters, andreplace trailingX characters inprefix with random characters.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use.

import { mkdtemp }from'node:fs/promises';import { join }from'node:path';import { tmpdir }from'node:os';try {awaitmkdtemp(join(tmpdir(),'foo-'));}catch (err) {console.error(err);}

ThefsPromises.mkdtemp() method will append the six randomly selectedcharacters directly to theprefix string. For instance, given a directory/tmp, if the intention is to create a temporary directorywithin/tmp, theprefix must end with a trailing platform-specific path separator(require('node:path').sep).

fsPromises.mkdtempDisposable(prefix[, options])#

Added in: v24.4.0

The resulting Promise holds an async-disposable object whosepath propertyholds the created directory path. When the object is disposed, the directoryand its contents will be removed asynchronously if it still exists. If thedirectory cannot be deleted, disposal will throw an error. The object has anasyncremove() method which will perform the same task.

Both this function and the disposal function on the resulting object areasync, so it should be used withawait +await using as inawait using dir = await fsPromises.mkdtempDisposable('prefix').

For detailed information, see the documentation offsPromises.mkdtemp().

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use.

fsPromises.open(path, flags[, mode])#

History
VersionChanges
v11.1.0

Theflags argument is now optional and defaults to'r'.

v10.0.0

Added in: v10.0.0

Opens a<FileHandle>.

Refer to the POSIXopen(2) documentation for more detail.

Some characters (< > : " / \ | ? *) are reserved under Windows as documentedbyNaming Files, Paths, and Namespaces. Under NTFS, if the filename containsa colon, Node.js will open a file system stream, as described bythis MSDN page.

fsPromises.opendir(path[, options])#

History
VersionChanges
v20.1.0, v18.17.0

Addedrecursive option.

v13.1.0, v12.16.0

ThebufferSize option was introduced.

v12.12.0

Added in: v12.12.0

Asynchronously open a directory for iterative scanning. See the POSIXopendir(3) documentation for more detail.

Creates an<fs.Dir>, which contains all further functions for reading fromand cleaning up the directory.

Theencoding option sets the encoding for thepath while opening thedirectory and subsequent read operations.

Example using async iteration:

import { opendir }from'node:fs/promises';try {const dir =awaitopendir('./');forawait (const direntof dir)console.log(dirent.name);}catch (err) {console.error(err);}

When using the async iterator, the<fs.Dir> object will be automaticallyclosed after the iterator exits.

fsPromises.readdir(path[, options])#

History
VersionChanges
v20.1.0, v18.17.0

Addedrecursive option.

v10.11.0

New optionwithFileTypes was added.

v10.0.0

Added in: v10.0.0

  • path<string> |<Buffer> |<URL>
  • options<string> |<Object>
    • encoding<string>Default:'utf8'
    • withFileTypes<boolean>Default:false
    • recursive<boolean> Iftrue, reads the contents of a directoryrecursively. In recursive mode, it will list all files, sub files, anddirectories.Default:false.
  • Returns:<Promise> Fulfills with an array of the names of the files inthe directory excluding'.' and'..'.

Reads the contents of a directory.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe filenames. If theencoding is set to'buffer', the filenames returnedwill be passed as<Buffer> objects.

Ifoptions.withFileTypes is set totrue, the returned array will contain<fs.Dirent> objects.

import { readdir }from'node:fs/promises';try {const files =awaitreaddir(path);for (const fileof files)console.log(file);}catch (err) {console.error(err);}

fsPromises.readFile(path[, options])#

History
VersionChanges
v15.2.0, v14.17.0

The options argument may include an AbortSignal to abort an ongoing readFile request.

v10.0.0

Added in: v10.0.0

Asynchronously reads the entire contents of a file.

If no encoding is specified (usingoptions.encoding), the data is returnedas a<Buffer> object. Otherwise, the data will be a string.

Ifoptions is a string, then it specifies the encoding.

When thepath is a directory, the behavior offsPromises.readFile() isplatform-specific. On macOS, Linux, and Windows, the promise will be rejectedwith an error. On FreeBSD, a representation of the directory's contents will bereturned.

An example of reading apackage.json file located in the same directory of therunning code:

import { readFile }from'node:fs/promises';try {const filePath =newURL('./package.json',import.meta.url);const contents =awaitreadFile(filePath, {encoding:'utf8' });console.log(contents);}catch (err) {console.error(err.message);}const { readFile } =require('node:fs/promises');const { resolve } =require('node:path');asyncfunctionlogFile() {try {const filePath =resolve('./package.json');const contents =awaitreadFile(filePath, {encoding:'utf8' });console.log(contents);  }catch (err) {console.error(err.message);  }}logFile();

It is possible to abort an ongoingreadFile using an<AbortSignal>. If arequest is aborted the promise returned is rejected with anAbortError:

import { readFile }from'node:fs/promises';try {const controller =newAbortController();const { signal } = controller;const promise =readFile(fileName, { signal });// Abort the request before the promise settles.  controller.abort();await promise;}catch (err) {// When a request is aborted - err is an AbortErrorconsole.error(err);}

Aborting an ongoing request does not abort individual operatingsystem requests but rather the internal bufferingfs.readFile performs.

Any specified<FileHandle> has to support reading.

fsPromises.readlink(path[, options])#

Added in: v10.0.0

Reads the contents of the symbolic link referred to bypath. See the POSIXreadlink(2) documentation for more detail. The promise is fulfilled with thelinkString upon success.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe link path returned. If theencoding is set to'buffer', the link pathreturned will be passed as a<Buffer> object.

fsPromises.realpath(path[, options])#

Added in: v10.0.0

Determines the actual location ofpath using the same semantics as thefs.realpath.native() function.

Only paths that can be converted to UTF8 strings are supported.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe path. If theencoding is set to'buffer', the path returned will bepassed as a<Buffer> object.

On Linux, when Node.js is linked against musl libc, the procfs file system mustbe mounted on/proc in order for this function to work. Glibc does not havethis restriction.

fsPromises.rename(oldPath, newPath)#

Added in: v10.0.0

RenamesoldPath tonewPath.

fsPromises.rmdir(path[, options])#

History
VersionChanges
v16.0.0

UsingfsPromises.rmdir(path, { recursive: true }) on apath that is a file is no longer permitted and results in anENOENT error on Windows and anENOTDIR error on POSIX.

v16.0.0

UsingfsPromises.rmdir(path, { recursive: true }) on apath that does not exist is no longer permitted and results in aENOENT error.

v16.0.0

Therecursive option is deprecated, using it triggers a deprecation warning.

v14.14.0

Therecursive option is deprecated, usefsPromises.rm instead.

v13.3.0, v12.16.0

ThemaxBusyTries option is renamed tomaxRetries, and its default is 0. TheemfileWait option has been removed, andEMFILE errors use the same retry logic as other errors. TheretryDelay option is now supported.ENFILE errors are now retried.

v12.10.0

Therecursive,maxBusyTries, andemfileWait options are now supported.

v10.0.0

Added in: v10.0.0

  • path<string> |<Buffer> |<URL>
  • options<Object>
    • maxRetries<integer> If anEBUSY,EMFILE,ENFILE,ENOTEMPTY, orEPERM error is encountered, Node.js retries the operation with a linearbackoff wait ofretryDelay milliseconds longer on each try. This optionrepresents the number of retries. This option is ignored if therecursiveoption is nottrue.Default:0.
    • recursive<boolean> Iftrue, perform a recursive directory removal. Inrecursive mode, operations are retried on failure.Default:false.Deprecated.
    • retryDelay<integer> The amount of time in milliseconds to wait betweenretries. This option is ignored if therecursive option is nottrue.Default:100.
  • Returns:<Promise> Fulfills withundefined upon success.

Removes the directory identified bypath.

UsingfsPromises.rmdir() on a file (not a directory) results in thepromise being rejected with anENOENT error on Windows and anENOTDIRerror on POSIX.

To get a behavior similar to therm -rf Unix command, usefsPromises.rm() with options{ recursive: true, force: true }.

fsPromises.rm(path[, options])#

Added in: v14.14.0
  • path<string> |<Buffer> |<URL>
  • options<Object>
    • force<boolean> Whentrue, exceptions will be ignored ifpath doesnot exist.Default:false.
    • maxRetries<integer> If anEBUSY,EMFILE,ENFILE,ENOTEMPTY, orEPERM error is encountered, Node.js will retry the operation with a linearbackoff wait ofretryDelay milliseconds longer on each try. This optionrepresents the number of retries. This option is ignored if therecursiveoption is nottrue.Default:0.
    • recursive<boolean> Iftrue, perform a recursive directory removal. Inrecursive mode operations are retried on failure.Default:false.
    • retryDelay<integer> The amount of time in milliseconds to wait betweenretries. This option is ignored if therecursive option is nottrue.Default:100.
  • Returns:<Promise> Fulfills withundefined upon success.

Removes files and directories (modeled on the standard POSIXrm utility).

fsPromises.stat(path[, options])#

History
VersionChanges
v10.5.0

Accepts an additionaloptions object to specify whether the numeric values returned should be bigint.

v10.0.0

Added in: v10.0.0

fsPromises.statfs(path[, options])#

Added in: v19.6.0, v18.15.0

fsPromises.symlink(target, path[, type])#

History
VersionChanges
v19.0.0

If thetype argument isnull or omitted, Node.js will autodetecttarget type and automatically selectdir orfile.

v10.0.0

Added in: v10.0.0

Creates a symbolic link.

Thetype argument is only used on Windows platforms and can be one of'dir','file', or'junction'. If thetype argument isnull, Node.js willautodetecttarget type and use'file' or'dir'. If thetarget does notexist,'file' will be used. Windows junction points require the destinationpath to be absolute. When using'junction', thetarget argument willautomatically be normalized to absolute path. Junction points on NTFS volumescan only point to directories.

fsPromises.truncate(path[, len])#

Added in: v10.0.0

Truncates (shortens or extends the length) of the content atpath tolenbytes.

fsPromises.unlink(path)#

Added in: v10.0.0

Ifpath refers to a symbolic link, then the link is removed without affectingthe file or directory to which that link refers. If thepath refers to a filepath that is not a symbolic link, the file is deleted. See the POSIXunlink(2)documentation for more detail.

fsPromises.utimes(path, atime, mtime)#

Added in: v10.0.0

Change the file system timestamps of the object referenced bypath.

Theatime andmtime arguments follow these rules:

  • Values can be either numbers representing Unix epoch time,Dates, or anumeric string like'123456789.0'.
  • If the value can not be converted to a number, or isNaN,Infinity, or-Infinity, anError will be thrown.

fsPromises.watch(filename[, options])#

Added in: v15.9.0, v14.18.0
  • filename<string> |<Buffer> |<URL>
  • options<string> |<Object>
    • persistent<boolean> Indicates whether the process should continue to runas long as files are being watched.Default:true.
    • recursive<boolean> Indicates whether all subdirectories should bewatched, or only the current directory. This applies when a directory isspecified, and only on supported platforms (Seecaveats).Default:false.
    • encoding<string> Specifies the character encoding to be used for thefilename passed to the listener.Default:'utf8'.
    • signal<AbortSignal> An<AbortSignal> used to signal when the watchershould stop.
    • maxQueue<number> Specifies the number of events to queue between iterationsof the<AsyncIterator> returned.Default:2048.
    • overflow<string> Either'ignore' or'throw' when there are more events to bequeued thanmaxQueue allows.'ignore' means overflow events are dropped and awarning is emitted, while'throw' means to throw an exception.Default:'ignore'.
  • Returns:<AsyncIterator> of objects with the properties:

Returns an async iterator that watches for changes onfilename, wherefilenameis either a file or a directory.

const { watch } =require('node:fs/promises');const ac =newAbortController();const { signal } = ac;setTimeout(() => ac.abort(),10000);(async () => {try {const watcher =watch(__filename, { signal });forawait (const eventof watcher)console.log(event);  }catch (err) {if (err.name ==='AbortError')return;throw err;  }})();

On most platforms,'rename' is emitted whenever a filename appears ordisappears in the directory.

All thecaveats forfs.watch() also apply tofsPromises.watch().

fsPromises.writeFile(file, data[, options])#

History
VersionChanges
v21.0.0, v20.10.0

Theflush option is now supported.

v15.14.0, v14.18.0

Thedata argument supportsAsyncIterable,Iterable, andStream.

v15.2.0, v14.17.0

The options argument may include an AbortSignal to abort an ongoing writeFile request.

v14.0.0

Thedata parameter won't coerce unsupported input to strings anymore.

v10.0.0

Added in: v10.0.0

Asynchronously writes data to a file, replacing the file if it already exists.data can be a string, a buffer, an<AsyncIterable>, or an<Iterable> object.

Theencoding option is ignored ifdata is a buffer.

Ifoptions is a string, then it specifies the encoding.

Themode option only affects the newly created file. Seefs.open()for more details.

Any specified<FileHandle> has to support writing.

It is unsafe to usefsPromises.writeFile() multiple times on the same filewithout waiting for the promise to be settled.

Similarly tofsPromises.readFile -fsPromises.writeFile is a conveniencemethod that performs multiplewrite calls internally to write the bufferpassed to it. For performance sensitive code consider usingfs.createWriteStream() orfilehandle.createWriteStream().

It is possible to use an<AbortSignal> to cancel anfsPromises.writeFile().Cancelation is "best effort", and some amount of data is likely stillto be written.

import { writeFile }from'node:fs/promises';import {Buffer }from'node:buffer';try {const controller =newAbortController();const { signal } = controller;const data =newUint8Array(Buffer.from('Hello Node.js'));const promise =writeFile('message.txt', data, { signal });// Abort the request before the promise settles.  controller.abort();await promise;}catch (err) {// When a request is aborted - err is an AbortErrorconsole.error(err);}

Aborting an ongoing request does not abort individual operatingsystem requests but rather the internal bufferingfs.writeFile performs.

fsPromises.constants#

Added in: v18.4.0, v16.17.0

Returns an object containing commonly used constants for file systemoperations. The object is the same asfs.constants. SeeFS constantsfor more details.

Callback API#

The callback APIs perform all operations asynchronously, without blocking theevent loop, then invoke a callback function upon completion or error.

The callback APIs use the underlying Node.js threadpool to perform filesystem operations off the event loop thread. These operations are notsynchronized or threadsafe. Care must be taken when performing multipleconcurrent modifications on the same file or data corruption may occur.

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

History
VersionChanges
v20.8.0

The constantsfs.F_OK,fs.R_OK,fs.W_OK andfs.X_OK which were present directly onfs are deprecated.

v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v6.3.0

The constants likefs.R_OK, etc which were present directly onfs were moved intofs.constants as a soft deprecation. Thus for Node.js< v6.3.0 usefs to access those constants, or do something like(fs.constants || fs).R_OK to work with all versions.

v0.11.15

Added in: v0.11.15

Tests a user's permissions for the file or directory specified bypath.Themode argument is an optional integer that specifies the accessibilitychecks to be performed.mode should be either the valuefs.constants.F_OKor a mask consisting of the bitwise OR of any offs.constants.R_OK,fs.constants.W_OK, andfs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). CheckFile access constants forpossible values ofmode.

The final argument,callback, is a callback function that is invoked witha possible error argument. If any of the accessibility checks fail, the errorargument will be anError object. The following examples check ifpackage.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 usefs.access() to check for the accessibility of a file before callingfs.open(),fs.readFile(), orfs.writeFile(). Doingso introduces a race condition, since other processes may change the file'sstate between the two calls. Instead, user code should open/read/write thefile 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 thefile; the "recommended" examples are better because they use the file directlyand handle the error, if any.

In general, check for the accessibility of a file only if the file will not beused directly, for example when its accessibility is a signal from anotherprocess.

On Windows, access-control policies (ACLs) on a directory may limit access toa file or directory. Thefs.access() function, however, does not check theACL and therefore may report that a path is accessible even if the ACL restrictsthe user from reading or writing to it.

fs.appendFile(path, data[, options], callback)#

History
VersionChanges
v21.1.0, v20.10.0

Theflush option is now supported.

v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v7.0.0

The passedoptions object will never be modified.

v5.0.0

Thefile parameter can be a file descriptor now.

v0.6.7

Added in: v0.6.7

Asynchronously append data to a file, creating the file if it does not yetexist.data can be a string or a<Buffer>.

Themode option only affects the newly created file. Seefs.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!');});

Ifoptions is a string, then it specifies the encoding:

import { appendFile }from'node:fs';appendFile('message.txt','data to append','utf8', callback);

Thepath may be specified as a numeric file descriptor that has been openedfor appending (usingfs.open() orfs.openSync()). The file descriptor willnot be closed automatically.

import { open, close, appendFile }from'node:fs';functioncloseFd(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;  }});

fs.chmod(path, mode, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.1.30

Added in: v0.1.30

Asynchronously changes the permissions of a file. No arguments other than apossible exception are given to the completion callback.

See the POSIXchmod(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!');});
File modes#

Themode argument used in both thefs.chmod() andfs.chmodSync()methods is a numeric bitmask created using a logical OR of the followingconstants:

ConstantOctalDescription
fs.constants.S_IRUSR0o400read by owner
fs.constants.S_IWUSR0o200write by owner
fs.constants.S_IXUSR0o100execute/search by owner
fs.constants.S_IRGRP0o40read by group
fs.constants.S_IWGRP0o20write by group
fs.constants.S_IXGRP0o10execute/search by group
fs.constants.S_IROTH0o4read by others
fs.constants.S_IWOTH0o2write by others
fs.constants.S_IXOTH0o1execute/search by others

An easier method of constructing themode is to use a sequence of threeoctal digits (e.g.765). The left-most digit (7 in the example), specifiesthe permissions for the file owner. The middle digit (6 in the example),specifies permissions for the group. The right-most digit (5 in the example),specifies the permissions for others.

NumberDescription
7read, write, and execute
6read and write
5read and execute
4read only
3write and execute
2write only
1execute only
0no permission

For example, the octal value0o765 means:

  • The owner may read, write, and execute the file.
  • The group may read and write the file.
  • Others may read and execute the file.

When using raw numbers where file modes are expected, any value larger than0o777 may result in platform-specific behaviors that are not supported to workconsistently. Therefore constants likeS_ISVTX,S_ISGID, orS_ISUID arenot exposed infs.constants.

Caveats: on Windows only the write permission can be changed, and thedistinction among the permissions of group, owner, or others is notimplemented.

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

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.1.97

Added in: v0.1.97

Asynchronously changes owner and group of a file. No arguments other than apossible exception are given to the completion callback.

See the POSIXchown(2) documentation for more detail.

fs.close(fd[, callback])#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v15.9.0, v14.17.0

A default callback is now used if one is not provided.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.0.2

Added in: v0.0.2

Closes the file descriptor. No arguments other than a possible exception aregiven to the completion callback.

Callingfs.close() on any file descriptor (fd) that is currently in usethrough any otherfs operation may lead to undefined behavior.

See the POSIXclose(2) documentation for more detail.

fs.copyFile(src, dest[, mode], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v14.0.0

Changedflags argument tomode and imposed stricter type validation.

v8.5.0

Added in: v8.5.0

Asynchronously copiessrc todest. By default,dest is overwritten if italready exists. No arguments other than a possible exception are given to thecallback function. Node.js makes no guarantees about the atomicity of the copyoperation. If an error occurs after the destination file has been opened forwriting, Node.js will attempt to remove the destination.

mode is an optional integer that specifies the behaviorof the copy operation. It is possible to create a mask consisting of the bitwiseOR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

  • fs.constants.COPYFILE_EXCL: The copy operation will fail ifdest alreadyexists.
  • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create acopy-on-write reflink. If the platform does not support copy-on-write, then afallback copy mechanism is used.
  • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt tocreate a copy-on-write reflink. If the platform does not supportcopy-on-write, then the operation will fail.
import { copyFile, constants }from'node:fs';functioncallback(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);

fs.cp(src, dest[, options], callback)#

History
VersionChanges
v22.3.0

This API is no longer experimental.

v20.1.0, v18.17.0

Accept an additionalmode option to specify the copy behavior as themode argument offs.copyFile().

v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v17.6.0, v16.15.0

Accepts an additionalverbatimSymlinks option to specify whether to perform path resolution for symlinks.

v16.7.0

Added in: v16.7.0

  • src<string> |<URL> source path to copy.
  • dest<string> |<URL> destination path to copy to.
  • options<Object>
    • dereference<boolean> dereference symlinks.Default:false.
    • errorOnExist<boolean> whenforce isfalse, and the destinationexists, throw an error.Default:false.
    • filter<Function> Function to filter copied files/directories. Returntrue to copy the item,false to ignore it. When ignoring a directory,all of its contents will be skipped as well. Can also return aPromisethat resolves totrue orfalseDefault:undefined.
      • src<string> source path to copy.
      • dest<string> destination path to copy to.
      • Returns:<boolean> |<Promise> A value that is coercible toboolean oraPromise that fulfils with such value.
    • force<boolean> overwrite existing file or directory. The copyoperation will ignore errors if you set this to false and the destinationexists. Use theerrorOnExist option to change this behavior.Default:true.
    • mode<integer> modifiers for copy operation.Default:0.Seemode flag offs.copyFile().
    • preserveTimestamps<boolean> Whentrue timestamps fromsrc willbe preserved.Default:false.
    • recursive<boolean> copy directories recursivelyDefault:false
    • verbatimSymlinks<boolean> Whentrue, path resolution for symlinks willbe skipped.Default:false
  • callback<Function>

Asynchronously copies the entire directory structure fromsrc todest,including subdirectories and files.

When copying a directory to another directory, globs are not supported andbehavior is similar tocp dir1/ dir2/.

fs.createReadStream(path[, options])#

History
VersionChanges
v16.10.0

Thefs option does not needopen method if anfd was provided.

v16.10.0

Thefs option does not needclose method ifautoClose isfalse.

v15.5.0

Add support forAbortSignal.

v15.4.0

Thefd option accepts FileHandle arguments.

v14.0.0

ChangeemitClose default totrue.

v13.6.0, v12.17.0

Thefs options allow overriding the usedfs implementation.

v12.10.0

EnableemitClose option.

v11.0.0

Impose new restrictions onstart andend, throwing more appropriate errors in cases when we cannot reasonably handle the input values.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

The passedoptions object will never be modified.

v2.3.0

The passedoptions object can be a string now.

v0.1.31

Added in: v0.1.31

options can includestart andend values to read a range of bytes fromthe file instead of the entire file. Bothstart andend are inclusive andstart counting at 0, allowed values are in the[0,Number.MAX_SAFE_INTEGER] range. Iffd is specified andstart isomitted orundefined,fs.createReadStream() reads sequentially from thecurrent file position. Theencoding can be any one of those accepted by<Buffer>.

Iffd is specified,ReadStream will ignore thepath argument and will usethe specified file descriptor. This means that no'open' event will beemitted.fd should be blocking; non-blockingfds should be passed to<net.Socket>.

Iffd points to a character device that only supports blocking reads(such as keyboard or sound card), read operations do not finish until data isavailable. This can prevent the process from exiting and the stream fromclosing naturally.

By default, the stream will emit a'close' event after it has beendestroyed. Set theemitClose option tofalse to change this behavior.

By providing thefs option, it is possible to override the correspondingfsimplementations foropen,read, andclose. When providing thefs option,an override forread is required. If nofd is provided, an override foropen is also required. IfautoClose istrue, an override forclose isalso 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);

IfautoClose is false, then the file descriptor won't be closed, even ifthere's an error. It is the application's responsibility to close it and makesure there's no file descriptor leak. IfautoClose is set to true (defaultbehavior), on'error' or'end' the file descriptor will be closedautomatically.

mode sets the file mode (permission and sticky bits), but only if thefile 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 });

Ifoptions is a string, then it specifies the encoding.

fs.createWriteStream(path[, options])#

History
VersionChanges
v21.0.0, v20.10.0

Theflush option is now supported.

v16.10.0

Thefs option does not needopen method if anfd was provided.

v16.10.0

Thefs option does not needclose method ifautoClose isfalse.

v15.5.0

Add support forAbortSignal.

v15.4.0

Thefd option accepts FileHandle arguments.

v14.0.0

ChangeemitClose default totrue.

v13.6.0, v12.17.0

Thefs options allow overriding the usedfs implementation.

v12.10.0

EnableemitClose option.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

The passedoptions object will never be modified.

v5.5.0

TheautoClose option is supported now.

v2.3.0

The passedoptions object can be a string now.

v0.1.31

Added in: v0.1.31

options may also include astart option to allow writing data at someposition past the beginning of the file, allowed values are in the[0,Number.MAX_SAFE_INTEGER] range. Modifying a file rather thanreplacing it may require theflags option to be set tor+ rather than thedefaultw. Theencoding can be any one of those accepted by<Buffer>.

IfautoClose is set to true (default behavior) on'error' or'finish'the file descriptor will be closed automatically. IfautoClose 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 nofile descriptor leak.

By default, the stream will emit a'close' event after it has beendestroyed. Set theemitClose option tofalse to change this behavior.

By providing thefs option it is possible to override the correspondingfsimplementations foropen,write,writev, andclose. Overridingwrite()withoutwritev() can reduce performance as some optimizations (_writev())will be disabled. When providing thefs option, overrides for at least one ofwrite andwritev are required. If nofd option is supplied, an overrideforopen is also required. IfautoClose istrue, an override forcloseis also required.

Like<fs.ReadStream>, iffd is specified,<fs.WriteStream> will ignore thepath argument and will use the specified file descriptor. This means that no'open' event will be emitted.fd should be blocking; non-blockingfdsshould be passed to<net.Socket>.

Ifoptions is a string, then it specifies the encoding.

fs.exists(path, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v1.0.0

Deprecated since: v1.0.0

v0.0.2

Added in: v0.0.2

Stability: 0 - Deprecated: Usefs.stat() orfs.access() instead.

Test whether or not the element at the givenpath exists by checking with the file system.Then call thecallback 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 anerrparameter, optionally followed by other parameters. Thefs.exists() callbackhas only one boolean parameter. This is one reasonfs.access() is recommendedinstead offs.exists().

Ifpath is a symbolic link, it is followed. Thus, ifpath exists but pointsto a non-existent element, the callback will receive the valuefalse.

Usingfs.exists() to check for the existence of a file before callingfs.open(),fs.readFile(), orfs.writeFile() is not recommended. Doingso introduces a race condition, since other processes may change the file'sstate between the two calls. Instead, user code should open/read/write thefile 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 thefile; the "recommended" examples are better because they use the file directlyand handle the error, if any.

In general, check for the existence of a file only if the file won't beused directly, for example when its existence is a signal from anotherprocess.

fs.fchmod(fd, mode, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.4.7

Added in: v0.4.7

Sets the permissions on the file. No arguments other than a possible exceptionare given to the completion callback.

See the POSIXfchmod(2) documentation for more detail.

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

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.4.7

Added in: v0.4.7

Sets the owner of the file. No arguments other than a possible exception aregiven to the completion callback.

See the POSIXfchown(2) documentation for more detail.

fs.fdatasync(fd, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.1.96

Added in: v0.1.96

Forces all currently queued I/O operations associated with the file to theoperating system's synchronized I/O completion state. Refer to the POSIXfdatasync(2) documentation for details. No arguments other than a possibleexception are given to the completion callback.

fs.fstat(fd[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.5.0

Accepts an additionaloptions object to specify whether the numeric values returned should be bigint.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.1.95

Added in: v0.1.95

Invokes the callback with the<fs.Stats> for the file descriptor.

See the POSIXfstat(2) documentation for more detail.

fs.fsync(fd, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.1.96

Added in: v0.1.96

Request that all data for the open file descriptor is flushed to the storagedevice. The specific implementation is operating system and device specific.Refer to the POSIXfsync(2) documentation for more detail. No arguments otherthan a possible exception are given to the completion callback.

fs.ftruncate(fd[, len], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.8.6

Added in: v0.8.6

Truncates the file descriptor. No arguments other than a possible exception aregiven to the completion callback.

See the POSIXftruncate(2) documentation for more detail.

If the file referred to by the file descriptor was larger thanlen bytes, onlythe firstlen bytes will be retained in the file.

For example, the following program retains only the first four bytes of thefile:

import { open, close, ftruncate }from'node:fs';functioncloseFd(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 thanlen bytes, it is extended, and theextended part is filled with null bytes ('\0'):

Iflen is negative then0 will be used.

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

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v4.1.0

Numeric strings,NaN, andInfinity are now allowed time specifiers.

v0.4.2

Added in: v0.4.2

Change the file system timestamps of the object referenced by the supplied filedescriptor. Seefs.utimes().

fs.glob(pattern[, options], callback)#

History
VersionChanges
v24.1.0

Add support forURL instances forcwd option.

v24.0.0

Marking the API stable.

v23.7.0, v22.14.0

Add support forexclude option to accept glob patterns.

v22.2.0

Add support forwithFileTypes as an option.

v22.0.0

Added in: v22.0.0

  • pattern<string> |<string[]>

  • options<Object>

    • cwd<string> |<URL> current working directory.Default:process.cwd()
    • exclude<Function> |<string[]> Function to filter out files/directories or alist of glob patterns to be excluded. If a function is provided, returntrue to exclude the item,false to include it.Default:undefined.
    • withFileTypes<boolean>true if the glob should return paths as Dirents,false otherwise.Default:false.
  • callback<Function>

  • Retrieves the files matching the specified pattern.

import { glob }from'node:fs';glob('**/*.js',(err, matches) => {if (err)throw err;console.log(matches);});const { glob } =require('node:fs');glob('**/*.js',(err, matches) => {if (err)throw err;console.log(matches);});

fs.lchmod(path, mode, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v16.0.0

The error returned may be anAggregateError if more than one error is returned.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.4.7

Deprecated since: v0.4.7

Stability: 0 - Deprecated

Changes the permissions on a symbolic link. No arguments other than a possibleexception are given to the completion callback.

This method is only implemented on macOS.

See the POSIXlchmod(2) documentation for more detail.

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

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.6.0

This API is no longer deprecated.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.4.7

Documentation-only deprecation.

Set the owner of the symbolic link. No arguments other than a possibleexception are given to the completion callback.

See the POSIXlchown(2) documentation for more detail.

fs.lutimes(path, atime, mtime, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v14.5.0, v12.19.0

Added in: v14.5.0, v12.19.0

Changes the access and modification times of a file in the same way asfs.utimes(), with the difference that if the path refers to a symboliclink, then the link is not dereferenced: instead, the timestamps of thesymbolic link itself are changed.

No arguments other than a possible exception are given to the completioncallback.

fs.link(existingPath, newPath, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

TheexistingPath andnewPath parameters can be WHATWGURL objects usingfile: protocol. Support is currently stillexperimental.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.1.31

Added in: v0.1.31

Creates a new link from theexistingPath to thenewPath. See the POSIXlink(2) documentation for more detail. No arguments other than a possibleexception are given to the completion callback.

fs.lstat(path[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.5.0

Accepts an additionaloptions object to specify whether the numeric values returned should be bigint.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.1.30

Added in: v0.1.30

Retrieves the<fs.Stats> for the symbolic link referred to by the path.The callback gets two arguments(err, stats) wherestats is a<fs.Stats>object.lstat() is identical tostat(), except that ifpath is a symboliclink, then the link itself is stat-ed, not the file that it refers to.

See the POSIXlstat(2) documentation for more details.

fs.mkdir(path[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v13.11.0, v12.17.0

Inrecursive mode, the callback now receives the first created path as an argument.

v10.12.0

The second argument can now be anoptions object withrecursive andmode properties.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.1.8

Added in: v0.1.8

Asynchronously creates a directory.

The callback is given a possible exception and, ifrecursive istrue, thefirst directory path created,(err[, path]).path can still beundefined whenrecursive istrue, if no directory wascreated (for instance, if it was previously created).

The optionaloptions argument can be an integer specifyingmode (permissionand sticky bits), or an object with amode property and arecursiveproperty indicating whether parent directories should be created. Callingfs.mkdir() whenpath is a directory that exists results in an error onlywhenrecursive is false. Ifrecursive is false and the directory exists,anEEXIST 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, usingfs.mkdir() on the root directory even with recursion willresult in an error:

import { mkdir }from'node:fs';mkdir('/', {recursive:true },(err) => {// => [Error: EPERM: operation not permitted, mkdir 'C:\']});

See the POSIXmkdir(2) documentation for more details.

fs.mkdtemp(prefix[, options], callback)#

History
VersionChanges
v20.6.0, v18.19.0

Theprefix parameter now accepts buffers and URL.

v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v16.5.0, v14.18.0

Theprefix parameter now accepts an empty string.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v6.2.1

Thecallback parameter is optional now.

v5.10.0

Added in: v5.10.0

Creates a unique temporary directory.

Generates six random characters to be appended behind a requiredprefix to create a unique temporary directory. Due to platforminconsistencies, avoid trailingX characters inprefix. Some platforms,notably the BSDs, can return more than six random characters, and replacetrailingX characters inprefix with random characters.

The created directory path is passed as a string to the callback's secondparameter.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding 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});

Thefs.mkdtemp() method will append the six randomly selected charactersdirectly to theprefix string. For instance, given a directory/tmp, if theintention is to create a temporary directorywithin/tmp, theprefixmust end with a trailing platform-specific path separator(require('node:path').sep).

import { tmpdir }from'node:os';import { mkdtemp }from'node:fs';// The parent directory for the new temporary directoryconst 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.});

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

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v11.1.0

Theflags argument is now optional and defaults to'r'.

v9.9.0

Theas andas+ flags are supported now.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.0.2

Added in: v0.0.2

Asynchronous file open. See the POSIXopen(2) documentation for more details.

mode sets the file mode (permission and sticky bits), but only if the file wascreated. On Windows, only the write permission can be manipulated; seefs.chmod().

The callback gets two arguments(err, fd).

Some characters (< > : " / \ | ? *) are reserved under Windows as documentedbyNaming Files, Paths, and Namespaces. Under NTFS, if the filename containsa colon, Node.js will open a file system stream, as described bythis MSDN page.

Functions based onfs.open() exhibit this behavior as well:fs.writeFile(),fs.readFile(), etc.

fs.openAsBlob(path[, options])#

History
VersionChanges
v24.0.0

Marking the API stable.

v19.8.0

Added in: v19.8.0

Returns a<Blob> whose data is backed by the given file.

The file must not be modified after the<Blob> is created. Any modificationswill cause reading the<Blob> data to fail with aDOMException error.Synchronous stat operations on the file when theBlob is created, and beforeeach read in order to detect whether the file data has been modified on disk.

import { openAsBlob }from'node:fs';const blob =awaitopenAsBlob('the.file.txt');const ab =await blob.arrayBuffer();blob.stream();const { openAsBlob } =require('node:fs');(async () => {const blob =awaitopenAsBlob('the.file.txt');const ab =await blob.arrayBuffer();  blob.stream();})();

fs.opendir(path[, options], callback)#

History
VersionChanges
v20.1.0, v18.17.0

Addedrecursive option.

v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v13.1.0, v12.16.0

ThebufferSize option was introduced.

v12.12.0

Added in: v12.12.0

Asynchronously open a directory. See the POSIXopendir(3) documentation formore details.

Creates an<fs.Dir>, which contains all further functions for reading fromand cleaning up the directory.

Theencoding option sets the encoding for thepath while opening thedirectory and subsequent read operations.

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

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.10.0

Thebuffer parameter can now be anyTypedArray, or aDataView.

v7.4.0

Thebuffer parameter can now be aUint8Array.

v6.0.0

Thelength parameter can now be0.

v0.0.2

Added in: v0.0.2

Read data from the file specified byfd.

The callback is given the three arguments,(err, bytesRead, buffer).

If the file is not modified concurrently, the end-of-file is reached when thenumber of bytes read is zero.

If this method is invoked as itsutil.promisify()ed version, it returnsa promise for anObject withbytesRead andbuffer properties.

Thefs.read() method reads data from the file specifiedby the file descriptor (fd).Thelength argument indicates the maximum numberof bytes that Node.jswill attempt to read from the kernel.However, the actual number of bytes read (bytesRead) can be lowerthan the specifiedlength for various reasons.

For example:

  • If the file is shorter than the specifiedlength,bytesReadwill be set to the actual number of bytes read.
  • If the file encounters EOF (End of File) before the buffer couldbe filled, Node.js will read all available bytes until EOF is encountered,and thebytesRead parameter in the callback will indicatethe actual number of bytes read, which may be less than the specifiedlength.
  • If the file is on a slow networkfilesystemor encounters any other issue during reading,bytesRead can be lower than the specifiedlength.

Therefore, when usingfs.read(), it's important tocheck thebytesRead value todetermine how many bytes were actually read from the file.Depending on your applicationlogic, you may need to handle cases wherebytesReadis lower than the specifiedlength,such as by wrapping the read call in a loop if you requirea minimum amount of bytes.

This behavior is similar to the POSIXpreadv2 function.

fs.read(fd[, options], callback)#

History
VersionChanges
v13.11.0, v12.17.0

Options object can be passed in to make buffer, offset, length, and position optional.

v13.11.0, v12.17.0

Added in: v13.11.0, v12.17.0

Similar to thefs.read() function, this version takes an optionaloptions object. If nooptions object is specified, it will default with theabove values.

fs.read(fd, buffer[, options], callback)#

Added in: v18.2.0, v16.17.0

Similar to thefs.read() function, this version takes an optionaloptions object. If nooptions object is specified, it will default with theabove values.

fs.readdir(path[, options], callback)#

History
VersionChanges
v20.1.0, v18.17.0

Addedrecursive option.

v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.10.0

New optionwithFileTypes was added.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v6.0.0

Theoptions parameter was added.

v0.1.8

Added in: v0.1.8

Reads the contents of a directory. The callback gets two arguments(err, files)wherefiles is an array of the names of the files in the directory excluding'.' and'..'.

See the POSIXreaddir(3) documentation for more details.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe filenames passed to the callback. If theencoding is set to'buffer',the filenames returned will be passed as<Buffer> objects.

Ifoptions.withFileTypes is set totrue, thefiles array will contain<fs.Dirent> objects.

fs.readFile(path[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v16.0.0

The error returned may be anAggregateError if more than one error is returned.

v15.2.0, v14.17.0

The options argument may include an AbortSignal to abort an ongoing readFile request.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v5.1.0

Thecallback will always be called withnull as theerror parameter in case of success.

v5.0.0

Thepath parameter can be a file descriptor now.

v0.1.29

Added in: v0.1.29

Asynchronously 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), wheredata is thecontents of the file.

If no encoding is specified, then the raw buffer is returned.

Ifoptions 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 offs.readFile() andfs.readFileSync() is platform-specific. On macOS, Linux, and Windows, anerror will be returned. On FreeBSD, a representation of the directory's contentswill be returned.

import { readFile }from'node:fs';// macOS, Linux, and WindowsreadFile('<directory>',(err, data) => {// => [Error: EISDIR: illegal operation on a directory, read <directory>]});//  FreeBSDreadFile('<directory>',(err, data) => {// => null, <data>});

It is possible to abort an ongoing request using anAbortSignal. If arequest is aborted the callback is called with anAbortError:

import { readFile }from'node:fs';const controller =newAbortController();const signal = controller.signal;readFile(fileInfo[0].name, { signal },(err, buf) => {// ...});// When you want to abort the requestcontroller.abort();

Thefs.readFile() function buffers the entire file. To minimize memory costs,when possible prefer streaming viafs.createReadStream().

Aborting an ongoing request does not abort individual operatingsystem requests but rather the internal bufferingfs.readFile performs.

File descriptors#
  1. Any specified file descriptor has to support reading.
  2. If a file descriptor is specified as thepath, it will not be closedautomatically.
  3. The reading will begin at the current position. For example, if the filealready had'Hello World' and six bytes are read with the file descriptor,the call tofs.readFile() with the same file descriptor, would give'World', rather than'Hello World'.
Performance Considerations#

Thefs.readFile() method asynchronously reads the contents of a file intomemory one chunk at a time, allowing the event loop to turn between each chunk.This allows the read operation to have less impact on other activity that maybe using the underlying libuv thread pool but means that it will take longerto read a complete file into memory.

The additional read overhead can vary broadly on different systems and dependson the type of file being read. If the file type is not a regular file (a pipefor instance) and Node.js is unable to determine an actual file size, each readoperation will load on 64 KiB of data. For regular files, each read will process512 KiB of data.

For applications that require as-fast-as-possible reading of file contents, itis better to usefs.read() directly and for application code to managereading the full contents of the file itself.

The Node.js GitHub issue#25741 provides more information and a detailedanalysis on the performance offs.readFile() for multiple file sizes indifferent Node.js versions.

fs.readlink(path[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.1.31

Added in: v0.1.31

Reads the contents of the symbolic link referred to bypath. The callback getstwo arguments(err, linkString).

See the POSIXreadlink(2) documentation for more details.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe link path passed to the callback. If theencoding is set to'buffer',the link path returned will be passed as a<Buffer> object.

fs.readv(fd, buffers[, position], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v13.13.0, v12.17.0

Added in: v13.13.0, v12.17.0

Read from a file specified byfd and write to an array ofArrayBufferViewsusingreadv().

position is the offset from the beginning of the file from where datashould be read. Iftypeof position !== 'number', the data will be readfrom the current position.

The callback will be given three arguments:err,bytesRead, andbuffers.bytesRead is how many bytes were read from the file.

If this method is invoked as itsutil.promisify()ed version, it returnsa promise for anObject withbytesRead andbuffers properties.

fs.realpath(path[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v8.0.0

Pipe/Socket resolve support was added.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v6.4.0

Callingrealpath now works again for various edge cases on Windows.

v6.0.0

Thecache parameter was removed.

v0.1.31

Added in: v0.1.31

Asynchronously computes the canonical pathname by resolving.,.., andsymbolic links.

A canonical pathname is not necessarily unique. Hard links and bind mounts canexpose a file system entity through many pathnames.

This function behaves likerealpath(3), with some exceptions:

  1. No case conversion is performed on case-insensitive file systems.

  2. The maximum number of symbolic links is platform-independent and generally(much) higher than what the nativerealpath(3) implementation supports.

Thecallback gets two arguments(err, resolvedPath). May useprocess.cwdto resolve relative paths.

Only paths that can be converted to UTF8 strings are supported.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe path passed to the callback. If theencoding is set to'buffer',the path returned will be passed as a<Buffer> object.

Ifpath resolves to a socket or a pipe, the function will return a systemdependent name for that object.

A path that does not exist results in an ENOENT error.error.path is the absolute file path.

fs.realpath.native(path[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v9.2.0

Added in: v9.2.0

Asynchronousrealpath(3).

Thecallback gets two arguments(err, resolvedPath).

Only paths that can be converted to UTF8 strings are supported.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe path passed to the callback. If theencoding 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 mustbe mounted on/proc in order for this function to work. Glibc does not havethis restriction.

fs.rename(oldPath, newPath, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

TheoldPath andnewPath parameters can be WHATWGURL objects usingfile: protocol. Support is currently stillexperimental.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.0.2

Added in: v0.0.2

Asynchronously rename file atoldPath to the pathname providedasnewPath. In the case thatnewPath already exists, it willbe overwritten. If there is a directory atnewPath, an error willbe raised instead. No arguments other than a possible exception aregiven 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!');});

fs.rmdir(path[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v16.0.0

Usingfs.rmdir(path, { recursive: true }) on apath that is a file is no longer permitted and results in anENOENT error on Windows and anENOTDIR error on POSIX.

v16.0.0

Usingfs.rmdir(path, { recursive: true }) on apath that does not exist is no longer permitted and results in aENOENT error.

v16.0.0

Therecursive option is deprecated, using it triggers a deprecation warning.

v14.14.0

Therecursive option is deprecated, usefs.rm instead.

v13.3.0, v12.16.0

ThemaxBusyTries option is renamed tomaxRetries, and its default is 0. TheemfileWait option has been removed, andEMFILE errors use the same retry logic as other errors. TheretryDelay option is now supported.ENFILE errors are now retried.

v12.10.0

Therecursive,maxBusyTries, andemfileWait options are now supported.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameters can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.0.2

Added in: v0.0.2

  • path<string> |<Buffer> |<URL>
  • options<Object>
    • maxRetries<integer> If anEBUSY,EMFILE,ENFILE,ENOTEMPTY, orEPERM error is encountered, Node.js retries the operation with a linearbackoff wait ofretryDelay milliseconds longer on each try. This optionrepresents the number of retries. This option is ignored if therecursiveoption is nottrue.Default:0.
    • recursive<boolean> Iftrue, perform a recursive directory removal. Inrecursive mode, operations are retried on failure.Default:false.Deprecated.
    • retryDelay<integer> The amount of time in milliseconds to wait betweenretries. This option is ignored if therecursive option is nottrue.Default:100.
  • callback<Function>

Asynchronousrmdir(2). No arguments other than a possible exception are givento the completion callback.

Usingfs.rmdir() on a file (not a directory) results in anENOENT error onWindows and anENOTDIR error on POSIX.

To get a behavior similar to therm -rf Unix command, usefs.rm()with options{ recursive: true, force: true }.

fs.rm(path[, options], callback)#

History
VersionChanges
v17.3.0, v16.14.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v14.14.0

Added in: v14.14.0

  • path<string> |<Buffer> |<URL>
  • options<Object>
    • force<boolean> Whentrue, exceptions will be ignored ifpath doesnot exist.Default:false.
    • maxRetries<integer> If anEBUSY,EMFILE,ENFILE,ENOTEMPTY, orEPERM error is encountered, Node.js will retry the operation with a linearbackoff wait ofretryDelay milliseconds longer on each try. This optionrepresents the number of retries. This option is ignored if therecursiveoption is nottrue.Default:0.
    • recursive<boolean> Iftrue, perform a recursive removal. Inrecursive mode operations are retried on failure.Default:false.
    • retryDelay<integer> The amount of time in milliseconds to wait betweenretries. This option is ignored if therecursive option is nottrue.Default:100.
  • callback<Function>

Asynchronously removes files and directories (modeled on the standard POSIXrmutility). No arguments other than a possible exception are given to thecompletion callback.

fs.stat(path[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.5.0

Accepts an additionaloptions object to specify whether the numeric values returned should be bigint.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.0.2

Added in: v0.0.2

Asynchronousstat(2). The callback gets two arguments(err, stats) wherestats is an<fs.Stats> object.

In case of an error, theerr.code will be one ofCommon System Errors.

fs.stat() follows symbolic links. Usefs.lstat() to look at thelinks themselves.

Usingfs.stat() to check for the existence of a file before callingfs.open(),fs.readFile(), orfs.writeFile() is not recommended.Instead, user code should open/read/write the file directly and handle theerror raised if the file is not available.

To check if a file exists without manipulating it afterwards,fs.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:

trueStats {  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}falseStats {  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}

fs.statfs(path[, options], callback)#

Added in: v19.6.0, v18.15.0

Asynchronousstatfs(2). Returns information about the mounted file system whichcontainspath. The callback gets two arguments(err, stats) wherestatsis an<fs.StatFs> object.

In case of an error, theerr.code will be one ofCommon System Errors.

fs.symlink(target, path[, type], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v12.0.0

If thetype argument is left undefined, Node will autodetecttarget type and automatically selectdir orfile.

v7.6.0

Thetarget andpath parameters can be WHATWGURL objects usingfile: protocol. Support is currently stillexperimental.

v0.1.31

Added in: v0.1.31

Creates the link calledpath pointing totarget. No arguments other than apossible exception are given to the completion callback.

See the POSIXsymlink(2) documentation for more details.

Thetype argument is only available on Windows and ignored on other platforms.It can be set to'dir','file', or'junction'. If thetype argument isnull, Node.js will autodetecttarget type and use'file' or'dir'.If thetarget does not exist,'file' will be used. Windows junction pointsrequire the destination path to be absolute. When using'junction', thetarget argument will automatically be normalized to absolute path. Junctionpoints 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 linkmewtwo which points tomew in thesame directory:

$ tree ..├── mew└── mewtwo -> ./mew

fs.truncate(path[, len], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v16.0.0

The error returned may be anAggregateError if more than one error is returned.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.8.6

Added in: v0.8.6

Truncates the file. No arguments other than a possible exception aregiven to the completion callback. A file descriptor can also be passed as thefirst 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');});const { truncate } =require('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 thrownin the future.

See the POSIXtruncate(2) documentation for more details.

fs.unlink(path, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.0.2

Added in: v0.0.2

Asynchronously removes a file or symbolic link. No arguments other than apossible 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 adirectory, usefs.rmdir().

See the POSIXunlink(2) documentation for more details.

fs.unwatchFile(filename[, listener])#

Added in: v0.1.31

Stop watching for changes onfilename. Iflistener is specified, only thatparticular listener is removed. Otherwise,all listeners are removed,effectively stopping watching offilename.

Callingfs.unwatchFile() with a filename that is not being watched is ano-op, not an error.

Usingfs.watch() is more efficient thanfs.watchFile() andfs.unwatchFile().fs.watch() should be used instead offs.watchFile()andfs.unwatchFile() when possible.

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

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v8.0.0

NaN,Infinity, and-Infinity are no longer valid time specifiers.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v4.1.0

Numeric strings,NaN, andInfinity are now allowed time specifiers.

v0.4.2

Added in: v0.4.2

Change the file system timestamps of the object referenced bypath.

Theatime andmtime 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 isNaN,Infinity, or-Infinity, anError will be thrown.

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

History
VersionChanges
v19.1.0

Added recursive support for Linux, AIX and IBMi.

v15.9.0, v14.17.0

Added support for closing the watcher with an AbortSignal.

v7.6.0

Thefilename parameter can be a WHATWGURL object usingfile: protocol.

v7.0.0

The passedoptions object will never be modified.

v0.5.10

Added in: v0.5.10

Watch for changes onfilename, wherefilename is either a file or adirectory.

The second argument is optional. Ifoptions is provided as a string, itspecifies theencoding. Otherwiseoptions should be passed as an object.

The listener callback gets two arguments(eventType, filename).eventTypeis either'rename' or'change', andfilename is the name of the filewhich triggered the event.

On most platforms,'rename' is emitted whenever a filename appears ordisappears 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 ofeventType.

If asignal is passed, aborting the corresponding AbortController will closethe returned<fs.FSWatcher>.

Caveats#

Thefs.watch API is not 100% consistent across platforms, and isunavailable in some situations.

On Windows, no events will be emitted if the watched directory is moved orrenamed. AnEPERM error is reported when the watched directory is deleted.

Thefs.watch API does not provide any protection with respectto malicious actions on the file system. For example, on Windows it isimplemented by monitoring changes in a directory versus specific files. Thisallows substitution of a file and fs reporting changes on the new filewith the same filename.

Availability#

This feature depends on the underlying operating system providing a wayto be notified of file system changes.

  • On Linux systems, this usesinotify(7).
  • On BSD systems, this useskqueue(2).
  • On macOS, this useskqueue(2) for files andFSEvents fordirectories.
  • On SunOS systems (including Solaris and SmartOS), this usesevent ports.
  • On Windows systems, this feature depends onReadDirectoryChangesW.
  • On AIX systems, this feature depends onAHAFS, which must be enabled.
  • On IBM i systems, this feature is not supported.

If the underlying functionality is not available for some reason, thenfs.watch() will not be able to function and may throw an exception.For example, watching files or directories can be unreliable, and in somecases impossible, on network file systems (NFS, SMB, etc) or host file systemswhen using virtualization software such as Vagrant or Docker.

It is still possible to usefs.watchFile(), which uses stat polling, butthis method is slower and less reliable.

Inodes#

On Linux and macOS systems,fs.watch() resolves the path to aninode andwatches the inode. If the watched path is deleted and recreated, it is assigneda new inode. The watch will emit an event for the delete but will continuewatching theoriginal inode. Events for the new inode will not be emitted.This is expected behavior.

AIX files retain the same inode for the lifetime of a file. Saving and closing awatched file on AIX will result in two notifications (one for adding newcontent, and one for truncation).

Filename argument#

Providingfilename argument in the callback is only supported on Linux,macOS, Windows, and AIX. Even on supported platforms,filename is not alwaysguaranteed to be provided. Therefore, don't assume thatfilename argument isalways provided in the callback, and have some fallback logic if it isnull.

import { watch }from'node:fs';watch('somedir',(eventType, filename) => {console.log(`event type is:${eventType}`);if (filename) {console.log(`filename provided:${filename}`);  }else {console.log('filename not provided');  }});

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

History
VersionChanges
v10.5.0

Thebigint option is now supported.

v7.6.0

Thefilename parameter can be a WHATWGURL object usingfile: protocol.

v0.1.31

Added in: v0.1.31

Watch for changes onfilename. The callbacklistener will be called eachtime the file is accessed.

Theoptions argument may be omitted. If provided, it should be an object. Theoptions object may contain a boolean namedpersistent that indicateswhether the process should continue to run as long as files are being watched.Theoptions object may specify aninterval property indicating how often thetarget should be polled in milliseconds.

Thelistener gets two arguments the current stat object and the previousstat 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 offs.Stat. If thebigint option istrue,the numeric values in these objects are specified asBigInts.

To be notified when the file was modified, not just accessed, it is necessaryto comparecurr.mtimeMs andprev.mtimeMs.

When anfs.watchFile operation results in anENOENT error, itwill invoke the listener once, with all the fields zeroed (or, for dates, theUnix Epoch). If the file is created later on, the listener will be calledagain, with the latest stat objects. This is a change in functionality sincev0.10.

Usingfs.watch() is more efficient thanfs.watchFile andfs.unwatchFile.fs.watch should be used instead offs.watchFile andfs.unwatchFile when possible.

When a file being watched byfs.watchFile() disappears and reappears,then the contents ofprevious in the second callback event (the file'sreappearance) will be the same as the contents ofprevious in the firstcallback 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

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

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v14.0.0

Thebuffer parameter won't coerce unsupported input to strings anymore.

v10.10.0

Thebuffer parameter can now be anyTypedArray or aDataView.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.4.0

Thebuffer parameter can now be aUint8Array.

v7.2.0

Theoffset andlength parameters are optional now.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.0.2

Added in: v0.0.2

Writebuffer to the file specified byfd.

offset determines the part of the buffer to be written, andlength isan integer specifying the number of bytes to write.

position refers to the offset from the beginning of the file where this datashould be written. Iftypeof position !== 'number', the data will be writtenat the current position. Seepwrite(2).

The callback will be given three arguments(err, bytesWritten, buffer) wherebytesWritten specifies how manybytes were written frombuffer.

If this method is invoked as itsutil.promisify()ed version, it returnsa promise for anObject withbytesWritten andbuffer properties.

It is unsafe to usefs.write() multiple times on the same file without waitingfor the callback. For this scenario,fs.createWriteStream() isrecommended.

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 tothe end of the file.

fs.write(fd, buffer[, options], callback)#

Added in: v18.3.0, v16.17.0

Writebuffer to the file specified byfd.

Similar to the abovefs.write function, this version takes anoptionaloptions object. If nooptions object is specified, it willdefault with the above values.

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

History
VersionChanges
v19.0.0

Passing to thestring parameter an object with an owntoString function is no longer supported.

v17.8.0

Passing to thestring parameter an object with an owntoString function is deprecated.

v14.12.0

Thestring parameter will stringify an object with an explicittoString function.

v14.0.0

Thestring parameter won't coerce unsupported input to strings anymore.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.2.0

Theposition parameter is optional now.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v0.11.5

Added in: v0.11.5

Writestring to the file specified byfd. Ifstring is not a string,an exception is thrown.

position refers to the offset from the beginning of the file where this datashould be written. Iftypeof position !== 'number' the data will be written atthe current position. Seepwrite(2).

encoding is the expected string encoding.

The callback will receive the arguments(err, written, string) wherewrittenspecifies how manybytes the passed string required to be written. Byteswritten is not necessarily the same as string characters written. SeeBuffer.byteLength.

It is unsafe to usefs.write() multiple times on the same file without waitingfor the callback. For this scenario,fs.createWriteStream() isrecommended.

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 tothe end of the file.

On Windows, if the file descriptor is connected to the console (e.g.fd == 1orstdout) a string containing non-ASCII characters will not be renderedproperly by default, regardless of the encoding used.It is possible to configure the console to render UTF-8 properly by changing theactive codepage with thechcp 65001 command. See thechcp docs for moredetails.

fs.writeFile(file, data[, options], callback)#

History
VersionChanges
v21.0.0, v20.10.0

Theflush option is now supported.

v19.0.0

Passing to thestring parameter an object with an owntoString function is no longer supported.

v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v17.8.0

Passing to thestring parameter an object with an owntoString function is deprecated.

v16.0.0

The error returned may be anAggregateError if more than one error is returned.

v15.2.0, v14.17.0

The options argument may include an AbortSignal to abort an ongoing writeFile request.

v14.12.0

Thedata parameter will stringify an object with an explicittoString function.

v14.0.0

Thedata parameter won't coerce unsupported input to strings anymore.

v10.10.0

Thedata parameter can now be anyTypedArray or aDataView.

v10.0.0

Thecallback parameter is no longer optional. Not passing it will throw aTypeError at runtime.

v7.4.0

Thedata parameter can now be aUint8Array.

v7.0.0

Thecallback parameter is no longer optional. Not passing it will emit a deprecation warning with id DEP0013.

v5.0.0

Thefile parameter can be a file descriptor now.

v0.1.29

Added in: v0.1.29

Whenfile is a filename, asynchronously writes data to the file, replacing thefile if it already exists.data can be a string or a buffer.

Whenfile is a file descriptor, the behavior is similar to callingfs.write() directly (which is recommended). See the notes below on usinga file descriptor.

Theencoding option is ignored ifdata is a buffer.

Themode option only affects the newly created file. Seefs.open()for more details.

import { writeFile }from'node:fs';import {Buffer }from'node:buffer';const data =newUint8Array(Buffer.from('Hello Node.js'));writeFile('message.txt', data,(err) => {if (err)throw err;console.log('The file has been saved!');});

Ifoptions 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 usefs.writeFile() multiple times on the same file withoutwaiting for the callback. For this scenario,fs.createWriteStream() isrecommended.

Similarly tofs.readFile -fs.writeFile is a convenience method thatperforms multiplewrite calls internally to write the buffer passed to it.For performance sensitive code consider usingfs.createWriteStream().

It is possible to use an<AbortSignal> to cancel anfs.writeFile().Cancelation is "best effort", and some amount of data is likely stillto be written.

import { writeFile }from'node:fs';import {Buffer }from'node:buffer';const controller =newAbortController();const { signal } = controller;const data =newUint8Array(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 abortedcontroller.abort();

Aborting an ongoing request does not abort individual operatingsystem requests but rather the internal bufferingfs.writeFile performs.

Usingfs.writeFile() with file descriptors#

Whenfile is a file descriptor, the behavior is almost identical to directlycallingfs.write() like:

import { write }from'node:fs';import {Buffer }from'node:buffer';write(fd,Buffer.from(data, options.encoding), callback);

The difference from directly callingfs.write() is that under some unusualconditions,fs.write() might write only part of the buffer and need to beretried to write the remaining data, whereasfs.writeFile() retries untilthe data is entirely written (or an error occurs).

The implications of this are a common source of confusion. Inthe file descriptor case, the file is not replaced! The data is not necessarilywritten to the beginning of the file, and the file's original data may remainbefore and/or after the newly written data.

For example, iffs.writeFile() is called twice in a row, first to write thestring'Hello', then to write the string', World', the file would contain'Hello, World', and might contain some of the file's original data (dependingon the size of the original file, and the position of the file descriptor). Ifa file name had been used instead of a descriptor, the file would be guaranteedto contain only', World'.

fs.writev(fd, buffers[, position], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v12.9.0

Added in: v12.9.0

Write an array ofArrayBufferViews to the file specified byfd usingwritev().

position is the offset from the beginning of the file where this datashould be written. Iftypeof position !== 'number', the data will be writtenat the current position.

The callback will be given three arguments:err,bytesWritten, andbuffers.bytesWritten is how many bytes were written frombuffers.

If this method isutil.promisify()ed, it returns a promise for anObject withbytesWritten andbuffers properties.

It is unsafe to usefs.writev() multiple times on the same file withoutwaiting for the callback. For this scenario, usefs.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 tothe end of the file.

Synchronous API#

The synchronous APIs perform all operations synchronously, blocking theevent loop until the operation completes or fails.

fs.accessSync(path[, mode])#

History
VersionChanges
v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.11.15

Added in: v0.11.15

Synchronously tests a user's permissions for the file or directory specifiedbypath. Themode argument is an optional integer that specifies theaccessibility checks to be performed.mode should be either the valuefs.constants.F_OK or a mask consisting of the bitwise OR of any offs.constants.R_OK,fs.constants.W_OK, andfs.constants.X_OK (e.g.fs.constants.W_OK | fs.constants.R_OK). CheckFile access constants forpossible values ofmode.

If any of the accessibility checks fail, anError will be thrown. Otherwise,the method will returnundefined.

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])#

History
VersionChanges
v21.1.0, v20.10.0

Theflush option is now supported.

v7.0.0

The passedoptions object will never be modified.

v5.0.0

Thefile parameter can be a file descriptor now.

v0.6.7

Added in: v0.6.7

Synchronously append data to a file, creating the file if it does not yetexist.data can be a string or a<Buffer>.

Themode option only affects the newly created file. Seefs.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 */}

Ifoptions is a string, then it specifies the encoding:

import { appendFileSync }from'node:fs';appendFileSync('message.txt','data to append','utf8');

Thepath may be specified as a numeric file descriptor that has been openedfor appending (usingfs.open() orfs.openSync()). The file descriptor willnot 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(path, mode)#

History
VersionChanges
v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.6.7

Added in: v0.6.7

For detailed information, see the documentation of the asynchronous version ofthis API:fs.chmod().

See the POSIXchmod(2) documentation for more detail.

fs.chownSync(path, uid, gid)#

History
VersionChanges
v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.1.97

Added in: v0.1.97

Synchronously changes owner and group of a file. Returnsundefined.This is the synchronous version offs.chown().

See the POSIXchown(2) documentation for more detail.

fs.closeSync(fd)#

Added in: v0.1.21

Closes the file descriptor. Returnsundefined.

Callingfs.closeSync() on any file descriptor (fd) that is currently in usethrough any otherfs operation may lead to undefined behavior.

See the POSIXclose(2) documentation for more detail.

fs.copyFileSync(src, dest[, mode])#

History
VersionChanges
v14.0.0

Changedflags argument tomode and imposed stricter type validation.

v8.5.0

Added in: v8.5.0

Synchronously copiessrc todest. By default,dest is overwritten if italready exists. Returnsundefined. Node.js makes no guarantees about theatomicity of the copy operation. If an error occurs after the destination filehas been opened for writing, Node.js will attempt to remove the destination.

mode is an optional integer that specifies the behaviorof the copy operation. It is possible to create a mask consisting of the bitwiseOR of two or more values (e.g.fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).

  • fs.constants.COPYFILE_EXCL: The copy operation will fail ifdest alreadyexists.
  • fs.constants.COPYFILE_FICLONE: The copy operation will attempt to create acopy-on-write reflink. If the platform does not support copy-on-write, then afallback copy mechanism is used.
  • fs.constants.COPYFILE_FICLONE_FORCE: The copy operation will attempt tocreate a copy-on-write reflink. If the platform does not supportcopy-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(src, dest[, options])#

History
VersionChanges
v22.3.0

This API is no longer experimental.

v20.1.0, v18.17.0

Accept an additionalmode option to specify the copy behavior as themode argument offs.copyFile().

v17.6.0, v16.15.0

Accepts an additionalverbatimSymlinks option to specify whether to perform path resolution for symlinks.

v16.7.0

Added in: v16.7.0

  • src<string> |<URL> source path to copy.
  • dest<string> |<URL> destination path to copy to.
  • options<Object>
    • dereference<boolean> dereference symlinks.Default:false.
    • errorOnExist<boolean> whenforce isfalse, and the destinationexists, throw an error.Default:false.
    • filter<Function> Function to filter copied files/directories. Returntrue to copy the item,false to ignore it. When ignoring a directory,all of its contents will be skipped as well.Default:undefined
      • src<string> source path to copy.
      • dest<string> destination path to copy to.
      • Returns:<boolean> Any non-Promise value that is coercibletoboolean.
    • force<boolean> overwrite existing file or directory. The copyoperation will ignore errors if you set this to false and the destinationexists. Use theerrorOnExist option to change this behavior.Default:true.
    • mode<integer> modifiers for copy operation.Default:0.Seemode flag offs.copyFileSync().
    • preserveTimestamps<boolean> Whentrue timestamps fromsrc willbe preserved.Default:false.
    • recursive<boolean> copy directories recursivelyDefault:false
    • verbatimSymlinks<boolean> Whentrue, path resolution for symlinks willbe skipped.Default:false

Synchronously copies the entire directory structure fromsrc todest,including subdirectories and files.

When copying a directory to another directory, globs are not supported andbehavior is similar tocp dir1/ dir2/.

fs.existsSync(path)#

History
VersionChanges
v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.1.21

Added in: v0.1.21

Returnstrue if the path exists,false otherwise.

For detailed information, see the documentation of the asynchronous version ofthis API:fs.exists().

fs.exists() is deprecated, butfs.existsSync() is not. Thecallbackparameter tofs.exists() accepts parameters that are inconsistent with otherNode.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)#

Added in: v0.4.7

Sets the permissions on the file. Returnsundefined.

See the POSIXfchmod(2) documentation for more detail.

fs.fchownSync(fd, uid, gid)#

Added in: v0.4.7

Sets the owner of the file. Returnsundefined.

See the POSIXfchown(2) documentation for more detail.

fs.fdatasyncSync(fd)#

Added in: v0.1.96

Forces all currently queued I/O operations associated with the file to theoperating system's synchronized I/O completion state. Refer to the POSIXfdatasync(2) documentation for details. Returnsundefined.

fs.fstatSync(fd[, options])#

History
VersionChanges
v10.5.0

Accepts an additionaloptions object to specify whether the numeric values returned should be bigint.

v0.1.95

Added in: v0.1.95

Retrieves the<fs.Stats> for the file descriptor.

See the POSIXfstat(2) documentation for more detail.

fs.fsyncSync(fd)#

Added in: v0.1.96

Request that all data for the open file descriptor is flushed to the storagedevice. The specific implementation is operating system and device specific.Refer to the POSIXfsync(2) documentation for more detail. Returnsundefined.

fs.ftruncateSync(fd[, len])#

Added in: v0.8.6

Truncates the file descriptor. Returnsundefined.

For detailed information, see the documentation of the asynchronous version ofthis API:fs.ftruncate().

fs.futimesSync(fd, atime, mtime)#

History
VersionChanges
v4.1.0

Numeric strings,NaN, andInfinity are now allowed time specifiers.

v0.4.2

Added in: v0.4.2

Synchronous version offs.futimes(). Returnsundefined.

fs.globSync(pattern[, options])#

History
VersionChanges
v24.1.0

Add support forURL instances forcwd option.

v24.0.0

Marking the API stable.

v23.7.0, v22.14.0

Add support forexclude option to accept glob patterns.

v22.2.0

Add support forwithFileTypes as an option.

v22.0.0

Added in: v22.0.0

  • pattern<string> |<string[]>
  • options<Object>
    • cwd<string> |<URL> current working directory.Default:process.cwd()
    • exclude<Function> |<string[]> Function to filter out files/directories or alist of glob patterns to be excluded. If a function is provided, returntrue to exclude the item,false to include it.Default:undefined.
    • withFileTypes<boolean>true if the glob should return paths as Dirents,false otherwise.Default:false.
  • Returns:<string[]> paths of files that match the pattern.
import { globSync }from'node:fs';console.log(globSync('**/*.js'));const { globSync } =require('node:fs');console.log(globSync('**/*.js'));

fs.lchmodSync(path, mode)#

Deprecated since: v0.4.7

Stability: 0 - Deprecated

Changes the permissions on a symbolic link. Returnsundefined.

This method is only implemented on macOS.

See the POSIXlchmod(2) documentation for more detail.

fs.lchownSync(path, uid, gid)#

History
VersionChanges
v10.6.0

This API is no longer deprecated.

v0.4.7

Documentation-only deprecation.

Set the owner for the path. Returnsundefined.

See the POSIXlchown(2) documentation for more details.

fs.lutimesSync(path, atime, mtime)#

Added in: v14.5.0, v12.19.0

Change the file system timestamps of the symbolic link referenced bypath.Returnsundefined, or throws an exception when parameters are incorrect orthe operation fails. This is the synchronous version offs.lutimes().

fs.linkSync(existingPath, newPath)#

History
VersionChanges
v7.6.0

TheexistingPath andnewPath parameters can be WHATWGURL objects usingfile: protocol. Support is currently stillexperimental.

v0.1.31

Added in: v0.1.31

Creates a new link from theexistingPath to thenewPath. See the POSIXlink(2) documentation for more detail. Returnsundefined.

fs.lstatSync(path[, options])#

History
VersionChanges
v15.3.0, v14.17.0

Accepts athrowIfNoEntry option to specify whether an exception should be thrown if the entry does not exist.

v10.5.0

Accepts an additionaloptions object to specify whether the numeric values returned should be bigint.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.1.30

Added in: v0.1.30

Retrieves the<fs.Stats> for the symbolic link referred to bypath.

See the POSIXlstat(2) documentation for more details.

fs.mkdirSync(path[, options])#

History
VersionChanges
v13.11.0, v12.17.0

Inrecursive mode, the first created path is returned now.

v10.12.0

The second argument can now be anoptions object withrecursive andmode properties.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.1.21

Added in: v0.1.21

Synchronously creates a directory. Returnsundefined, or ifrecursive istrue, the first directory path created.This is the synchronous version offs.mkdir().

See the POSIXmkdir(2) documentation for more details.

fs.mkdtempSync(prefix[, options])#

History
VersionChanges
v20.6.0, v18.19.0

Theprefix parameter now accepts buffers and URL.

v16.5.0, v14.18.0

Theprefix parameter now accepts an empty string.

v5.10.0

Added in: v5.10.0

Returns the created directory path.

For detailed information, see the documentation of the asynchronous version ofthis API:fs.mkdtemp().

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use.

fs.mkdtempDisposableSync(prefix[, options])#

Added in: v24.4.0

Returns a disposable object whosepath property holds the created directorypath. When the object is disposed, the directory and its contents will beremoved if it still exists. If the directory cannot be deleted, disposal willthrow an error. The object has aremove() method which will perform the sametask.

For detailed information, see the documentation offs.mkdtemp().

There is no callback-based version of this API because it is designed for usewith theusing syntax.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use.

fs.opendirSync(path[, options])#

History
VersionChanges
v20.1.0, v18.17.0

Addedrecursive option.

v13.1.0, v12.16.0

ThebufferSize option was introduced.

v12.12.0

Added in: v12.12.0

Synchronously open a directory. Seeopendir(3).

Creates an<fs.Dir>, which contains all further functions for reading fromand cleaning up the directory.

Theencoding option sets the encoding for thepath while opening thedirectory and subsequent read operations.

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

History
VersionChanges
v11.1.0

Theflags argument is now optional and defaults to'r'.

v9.9.0

Theas andas+ flags are supported now.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.1.21

Added in: v0.1.21

Returns an integer representing the file descriptor.

For detailed information, see the documentation of the asynchronous version ofthis API:fs.open().

fs.readdirSync(path[, options])#

History
VersionChanges
v20.1.0, v18.17.0

Addedrecursive option.

v10.10.0

New optionwithFileTypes was added.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.1.21

Added in: v0.1.21

Reads the contents of the directory.

See the POSIXreaddir(3) documentation for more details.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe filenames returned. If theencoding is set to'buffer',the filenames returned will be passed as<Buffer> objects.

Ifoptions.withFileTypes is set totrue, the result will contain<fs.Dirent> objects.

fs.readFileSync(path[, options])#

History
VersionChanges
v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v5.0.0

Thepath parameter can be a file descriptor now.

v0.1.8

Added in: v0.1.8

Returns the contents of thepath.

For detailed information, see the documentation of the asynchronous version ofthis API:fs.readFile().

If theencoding option is specified then this function returns astring. Otherwise it returns a buffer.

Similar tofs.readFile(), when the path is a directory, the behavior offs.readFileSync() is platform-specific.

import { readFileSync }from'node:fs';// macOS, Linux, and WindowsreadFileSync('<directory>');// => [Error: EISDIR: illegal operation on a directory, read <directory>]//  FreeBSDreadFileSync('<directory>');// => <data>

fs.readlinkSync(path[, options])#

History
VersionChanges
v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.1.31

Added in: v0.1.31

Returns the symbolic link's string value.

See the POSIXreadlink(2) documentation for more details.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe link path returned. If theencoding is set to'buffer',the link path returned will be passed as a<Buffer> object.

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

History
VersionChanges
v10.10.0

Thebuffer parameter can now be anyTypedArray or aDataView.

v6.0.0

Thelength parameter can now be0.

v0.1.21

Added in: v0.1.21

Returns the number ofbytesRead.

For detailed information, see the documentation of the asynchronous version ofthis API:fs.read().

fs.readSync(fd, buffer[, options])#

History
VersionChanges
v13.13.0, v12.17.0

Options object can be passed in to make offset, length, and position optional.

v13.13.0, v12.17.0

Added in: v13.13.0, v12.17.0

Returns the number ofbytesRead.

Similar to the abovefs.readSync function, this version takes an optionaloptions object.If nooptions object is specified, it will default with the above values.

For detailed information, see the documentation of the asynchronous version ofthis API:fs.read().

fs.readvSync(fd, buffers[, position])#

Added in: v13.13.0, v12.17.0

For detailed information, see the documentation of the asynchronous version ofthis API:fs.readv().

fs.realpathSync(path[, options])#

History
VersionChanges
v8.0.0

Pipe/Socket resolve support was added.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v6.4.0

CallingrealpathSync now works again for various edge cases on Windows.

v6.0.0

Thecache parameter was removed.

v0.1.31

Added in: v0.1.31

Returns the resolved pathname.

For detailed information, see the documentation of the asynchronous version ofthis API:fs.realpath().

fs.realpathSync.native(path[, options])#

Added in: v9.2.0

Synchronousrealpath(3).

Only paths that can be converted to UTF8 strings are supported.

The optionaloptions argument can be a string specifying an encoding, or anobject with anencoding property specifying the character encoding to use forthe path returned. If theencoding 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 mustbe mounted on/proc in order for this function to work. Glibc does not havethis restriction.

fs.renameSync(oldPath, newPath)#

History
VersionChanges
v7.6.0

TheoldPath andnewPath parameters can be WHATWGURL objects usingfile: protocol. Support is currently stillexperimental.

v0.1.21

Added in: v0.1.21

Renames the file fromoldPath tonewPath. Returnsundefined.

See the POSIXrename(2) documentation for more details.

fs.rmdirSync(path[, options])#

History
VersionChanges
v16.0.0

Usingfs.rmdirSync(path, { recursive: true }) on apath that is a file is no longer permitted and results in anENOENT error on Windows and anENOTDIR error on POSIX.

v16.0.0

Usingfs.rmdirSync(path, { recursive: true }) on apath that does not exist is no longer permitted and results in aENOENT error.

v16.0.0

Therecursive option is deprecated, using it triggers a deprecation warning.

v14.14.0

Therecursive option is deprecated, usefs.rmSync instead.

v13.3.0, v12.16.0

ThemaxBusyTries option is renamed tomaxRetries, and its default is 0. TheemfileWait option has been removed, andEMFILE errors use the same retry logic as other errors. TheretryDelay option is now supported.ENFILE errors are now retried.

v12.10.0

Therecursive,maxBusyTries, andemfileWait options are now supported.

v7.6.0

Thepath parameters can be a WHATWGURL object usingfile: protocol.

v0.1.21

Added in: v0.1.21

  • path<string> |<Buffer> |<URL>
  • options<Object>
    • maxRetries<integer> If anEBUSY,EMFILE,ENFILE,ENOTEMPTY, orEPERM error is encountered, Node.js retries the operation with a linearbackoff wait ofretryDelay milliseconds longer on each try. This optionrepresents the number of retries. This option is ignored if therecursiveoption is nottrue.Default:0.
    • recursive<boolean> Iftrue, perform a recursive directory removal. Inrecursive mode, operations are retried on failure.Default:false.Deprecated.
    • retryDelay<integer> The amount of time in milliseconds to wait betweenretries. This option is ignored if therecursive option is nottrue.Default:100.

Synchronousrmdir(2). Returnsundefined.

Usingfs.rmdirSync() on a file (not a directory) results in anENOENT erroron Windows and anENOTDIR error on POSIX.

To get a behavior similar to therm -rf Unix command, usefs.rmSync()with options{ recursive: true, force: true }.

fs.rmSync(path[, options])#

History
VersionChanges
v17.3.0, v16.14.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v14.14.0

Added in: v14.14.0

  • path<string> |<Buffer> |<URL>
  • options<Object>
    • force<boolean> Whentrue, exceptions will be ignored ifpath doesnot exist.Default:false.
    • maxRetries<integer> If anEBUSY,EMFILE,ENFILE,ENOTEMPTY, orEPERM error is encountered, Node.js will retry the operation with a linearbackoff wait ofretryDelay milliseconds longer on each try. This optionrepresents the number of retries. This option is ignored if therecursiveoption is nottrue.Default:0.
    • recursive<boolean> Iftrue, perform a recursive directory removal. Inrecursive mode operations are retried on failure.Default:false.
    • retryDelay<integer> The amount of time in milliseconds to wait betweenretries. This option is ignored if therecursive option is nottrue.Default:100.

Synchronously removes files and directories (modeled on the standard POSIXrmutility). Returnsundefined.

fs.statSync(path[, options])#

History
VersionChanges
v15.3.0, v14.17.0

Accepts athrowIfNoEntry option to specify whether an exception should be thrown if the entry does not exist.

v10.5.0

Accepts an additionaloptions object to specify whether the numeric values returned should be bigint.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.1.21

Added in: v0.1.21

Retrieves the<fs.Stats> for the path.

fs.statfsSync(path[, options])#

Added in: v19.6.0, v18.15.0

Synchronousstatfs(2). Returns information about the mounted file system whichcontainspath.

In case of an error, theerr.code will be one ofCommon System Errors.

fs.symlinkSync(target, path[, type])#

History
VersionChanges
v12.0.0

If thetype argument is left undefined, Node will autodetecttarget type and automatically selectdir orfile.

v7.6.0

Thetarget andpath parameters can be WHATWGURL objects usingfile: protocol. Support is currently stillexperimental.

v0.1.31

Added in: v0.1.31

For detailed information, see the documentation of the asynchronous version ofthis API:fs.symlink().

fs.truncateSync(path[, len])#

Added in: v0.8.6

Truncates the file. Returnsundefined. A file descriptor can also bepassed as the first argument. In this case,fs.ftruncateSync() is called.

Passing a file descriptor is deprecated and may result in an error being thrownin the future.

fs.unlinkSync(path)#

History
VersionChanges
v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v0.1.21

Added in: v0.1.21

Synchronousunlink(2). Returnsundefined.

fs.utimesSync(path, atime, mtime)#

History
VersionChanges
v8.0.0

NaN,Infinity, and-Infinity are no longer valid time specifiers.

v7.6.0

Thepath parameter can be a WHATWGURL object usingfile: protocol.

v4.1.0

Numeric strings,NaN, andInfinity are now allowed time specifiers.

v0.4.2

Added in: v0.4.2

For detailed information, see the documentation of the asynchronous version ofthis API:fs.utimes().

fs.writeFileSync(file, data[, options])#

History
VersionChanges
v21.0.0, v20.10.0

Theflush option is now supported.

v19.0.0

Passing to thedata parameter an object with an owntoString function is no longer supported.

v17.8.0

Passing to thedata parameter an object with an owntoString function is deprecated.

v14.12.0

Thedata parameter will stringify an object with an explicittoString function.

v14.0.0

Thedata parameter won't coerce unsupported input to strings anymore.

v10.10.0

Thedata parameter can now be anyTypedArray or aDataView.

v7.4.0

Thedata parameter can now be aUint8Array.

v5.0.0

Thefile parameter can be a file descriptor now.

v0.1.29

Added in: v0.1.29

Themode option only affects the newly created file. Seefs.open()for more details.

For detailed information, see the documentation of the asynchronous version ofthis API:fs.writeFile().

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

History
VersionChanges
v14.0.0

Thebuffer parameter won't coerce unsupported input to strings anymore.

v10.10.0

Thebuffer parameter can now be anyTypedArray or aDataView.

v7.4.0

Thebuffer parameter can now be aUint8Array.

v7.2.0

Theoffset andlength parameters are optional now.

v0.1.21

Added in: v0.1.21

For detailed information, see the documentation of the asynchronous version ofthis API:fs.write(fd, buffer...).

fs.writeSync(fd, buffer[, options])#

Added in: v18.3.0, v16.17.0

For detailed information, see the documentation of the asynchronous version ofthis API:fs.write(fd, buffer...).

fs.writeSync(fd, string[, position[, encoding]])#

History
VersionChanges
v14.0.0

Thestring parameter won't coerce unsupported input to strings anymore.

v7.2.0

Theposition parameter is optional now.

v0.11.5

Added in: v0.11.5

For detailed information, see the documentation of the asynchronous version ofthis API:fs.write(fd, string...).

fs.writevSync(fd, buffers[, position])#

Added in: v12.9.0

For detailed information, see the documentation of the asynchronous version ofthis API:fs.writev().

Common Objects#

The common objects are shared by all of the file system API variants(promise, callback, and synchronous).

Class:fs.Dir#

Added in: v12.12.0

A class representing a directory stream.

Created byfs.opendir(),fs.opendirSync(), orfsPromises.opendir().

import { opendir }from'node:fs/promises';try {const dir =awaitopendir('./');forawait (const direntof dir)console.log(dirent.name);}catch (err) {console.error(err);}

When using the async iterator, the<fs.Dir> object will be automaticallyclosed after the iterator exits.

dir.close()#
Added in: v12.12.0

Asynchronously close the directory's underlying resource handle.Subsequent reads will result in errors.

A promise is returned that will be fulfilled after the resource has beenclosed.

dir.close(callback)#
History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v12.12.0

Added in: v12.12.0

Asynchronously close the directory's underlying resource handle.Subsequent reads will result in errors.

Thecallback will be called after the resource handle has been closed.

dir.closeSync()#
Added in: v12.12.0

Synchronously close the directory's underlying resource handle.Subsequent reads will result in errors.

dir.path#
Added in: v12.12.0

The read-only path of this directory as was provided tofs.opendir(),fs.opendirSync(), orfsPromises.opendir().

dir.read()#
Added in: v12.12.0

Asynchronously read the next directory entry viareaddir(3) as an<fs.Dirent>.

A promise is returned that will be fulfilled with an<fs.Dirent>, ornullif there are no more directory entries to read.

Directory entries returned by this function are in no particular order asprovided by the operating system's underlying directory mechanisms.Entries added or removed while iterating over the directory might not beincluded in the iteration results.

dir.read(callback)#
Added in: v12.12.0

Asynchronously read the next directory entry viareaddir(3) as an<fs.Dirent>.

After the read is completed, thecallback will be called with an<fs.Dirent>, ornull if there are no more directory entries to read.

Directory entries returned by this function are in no particular order asprovided by the operating system's underlying directory mechanisms.Entries added or removed while iterating over the directory might not beincluded in the iteration results.

dir.readSync()#
Added in: v12.12.0

Synchronously read the next directory entry as an<fs.Dirent>. See thePOSIXreaddir(3) documentation for more detail.

If there are no more directory entries to read,null will be returned.

Directory entries returned by this function are in no particular order asprovided by the operating system's underlying directory mechanisms.Entries added or removed while iterating over the directory might not beincluded in the iteration results.

dir[Symbol.asyncIterator]()#
Added in: v12.12.0

Asynchronously iterates over the directory until all entries havebeen read. Refer to the POSIXreaddir(3) documentation for more detail.

Entries returned by the async iterator are always an<fs.Dirent>.Thenull case fromdir.read() is handled internally.

See<fs.Dir> for an example.

Directory entries returned by this iterator are in no particular order asprovided by the operating system's underlying directory mechanisms.Entries added or removed while iterating over the directory might not beincluded in the iteration results.

dir[Symbol.asyncDispose]()#
History
VersionChanges
v24.2.0

No longer experimental.

v24.1.0

Added in: v24.1.0

Callsdir.close() if the directory handle is open, and returns a promise thatfulfills when disposal is complete.

dir[Symbol.dispose]()#
History
VersionChanges
v24.2.0

No longer experimental.

v24.1.0

Added in: v24.1.0

Callsdir.closeSync() if the directory handle is open, and returnsundefined.

Class:fs.Dirent#

Added in: v10.10.0

A representation of a directory entry, which can be a file or a subdirectorywithin the directory, as returned by reading from an<fs.Dir>. Thedirectory entry is a combination of the file name and file type pairs.

Additionally, whenfs.readdir() orfs.readdirSync() is called withthewithFileTypes option set totrue, the resulting array is filled with<fs.Dirent> objects, rather than strings or<Buffer>s.

dirent.isBlockDevice()#
Added in: v10.10.0

Returnstrue if the<fs.Dirent> object describes a block device.

dirent.isCharacterDevice()#
Added in: v10.10.0

Returnstrue if the<fs.Dirent> object describes a character device.

dirent.isDirectory()#
Added in: v10.10.0

Returnstrue if the<fs.Dirent> object describes a file systemdirectory.

dirent.isFIFO()#
Added in: v10.10.0

Returnstrue if the<fs.Dirent> object describes a first-in-first-out(FIFO) pipe.

dirent.isFile()#
Added in: v10.10.0

Returnstrue if the<fs.Dirent> object describes a regular file.

dirent.isSocket()#
Added in: v10.10.0

Returnstrue if the<fs.Dirent> object describes a socket.

dirent.isSymbolicLink()#
Added in: v10.10.0

Returnstrue if the<fs.Dirent> object describes a symbolic link.

dirent.name#
Added in: v10.10.0

The file name that this<fs.Dirent> object refers to. The type of thisvalue is determined by theoptions.encoding passed tofs.readdir() orfs.readdirSync().

dirent.parentPath#
History
VersionChanges
v24.0.0

Marking the API stable.

v21.4.0, v20.12.0, v18.20.0

Added in: v21.4.0, v20.12.0, v18.20.0

The path to the parent directory of the file this<fs.Dirent> object refers to.

Class:fs.FSWatcher#

Added in: v0.5.8

A successful call tofs.watch() method will return a new<fs.FSWatcher>object.

All<fs.FSWatcher> objects emit a'change' event whenever a specific watchedfile is modified.

Event:'change'#
Added in: v0.5.8
  • eventType<string> The type of change event that has occurred
  • filename<string> |<Buffer> The filename that changed (if relevant/available)

Emitted when something changes in a watched directory or file.See more details infs.watch().

Thefilename argument may not be provided depending on operating systemsupport. Iffilename is provided, it will be provided as a<Buffer> iffs.watch() is called with itsencoding option set to'buffer', otherwisefilename will be a UTF-8 string.

import { watch }from'node:fs';// Example when handled through fs.watch() listenerwatch('./tmp', {encoding:'buffer' },(eventType, filename) => {if (filename) {console.log(filename);// Prints: <Buffer ...>  }});
Event:'close'#
Added in: v10.0.0

Emitted when the watcher stops watching for changes. The closed<fs.FSWatcher> object is no longer usable in the event handler.

Event:'error'#
Added in: v0.5.8

Emitted when an error occurs while watching the file. The errored<fs.FSWatcher> object is no longer usable in the event handler.

watcher.close()#
Added in: v0.5.8

Stop watching for changes on the given<fs.FSWatcher>. Once stopped, the<fs.FSWatcher> object is no longer usable.

watcher.ref()#
Added in: v14.3.0, v12.20.0

When called, requests that the Node.js event loopnot exit so long as the<fs.FSWatcher> is active. Callingwatcher.ref() multiple times will haveno effect.

By default, all<fs.FSWatcher> objects are "ref'ed", making it normallyunnecessary to callwatcher.ref() unlesswatcher.unref() had beencalled previously.

watcher.unref()#
Added in: v14.3.0, v12.20.0

When called, the active<fs.FSWatcher> object will not require the Node.jsevent loop to remain active. If there is no other activity keeping theevent loop running, the process may exit before the<fs.FSWatcher> object'scallback is invoked. Callingwatcher.unref() multiple times will haveno effect.

Class:fs.StatWatcher#

Added in: v14.3.0, v12.20.0

A successful call tofs.watchFile() method will return a new<fs.StatWatcher>object.

watcher.ref()#
Added in: v14.3.0, v12.20.0

When called, requests that the Node.js event loopnot exit so long as the<fs.StatWatcher> is active. Callingwatcher.ref() multiple times will haveno effect.

By default, all<fs.StatWatcher> objects are "ref'ed", making it normallyunnecessary to callwatcher.ref() unlesswatcher.unref() had beencalled previously.

watcher.unref()#
Added in: v14.3.0, v12.20.0

When called, the active<fs.StatWatcher> object will not require the Node.jsevent loop to remain active. If there is no other activity keeping theevent loop running, the process may exit before the<fs.StatWatcher> object'scallback is invoked. Callingwatcher.unref() multiple times will haveno effect.

Class:fs.ReadStream#

Added in: v0.1.93

Instances of<fs.ReadStream> are created and returned using thefs.createReadStream() function.

Event:'close'#
Added in: v0.1.93

Emitted when the<fs.ReadStream>'s underlying file descriptor has been closed.

Event:'open'#
Added in: v0.1.93

Emitted when the<fs.ReadStream>'s file descriptor has been opened.

Event:'ready'#
Added in: v9.11.0

Emitted when the<fs.ReadStream> is ready to be used.

Fires immediately after'open'.

readStream.bytesRead#
Added in: v6.4.0

The number of bytes that have been read so far.

readStream.path#
Added in: v0.1.93

The path to the file the stream is reading from as specified in the firstargument tofs.createReadStream(). Ifpath is passed as a string, thenreadStream.path will be a string. Ifpath is passed as a<Buffer>, thenreadStream.path will be a<Buffer>. Iffd is specified, thenreadStream.path will beundefined.

readStream.pending#
Added in: v11.2.0, v10.16.0

This property istrue if the underlying file has not been opened yet,i.e. before the'ready' event is emitted.

Class:fs.Stats#

History
VersionChanges
v22.0.0, v20.13.0

Public constructor is deprecated.

v8.1.0

Added times as numbers.

v0.1.21

Added in: v0.1.21

A<fs.Stats> object provides information about a file.

Objects returned fromfs.stat(),fs.lstat(),fs.fstat(), andtheir synchronous counterparts are of this type.Ifbigint in theoptions passed to those methods is true, the numeric valueswill bebigint instead ofnumber, and the object will contain additionalnanosecond-precision properties suffixed withNs.Stat objects are not to be created directly using thenew keyword.

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

bigint version:

BigIntStats {  dev: 2114n,  ino: 48064969n,  mode: 33188n,  nlink: 1n,  uid: 85n,  gid: 100n,  rdev: 0n,  size: 527n,  blksize: 4096n,  blocks: 8n,  atimeMs: 1318289051000n,  mtimeMs: 1318289051000n,  ctimeMs: 1318289051000n,  birthtimeMs: 1318289051000n,  atimeNs: 1318289051000000000n,  mtimeNs: 1318289051000000000n,  ctimeNs: 1318289051000000000n,  birthtimeNs: 1318289051000000000n,  atime: Mon, 10 Oct 2011 23:24:11 GMT,  mtime: Mon, 10 Oct 2011 23:24:11 GMT,  ctime: Mon, 10 Oct 2011 23:24:11 GMT,  birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
stats.isBlockDevice()#
Added in: v0.1.10

Returnstrue if the<fs.Stats> object describes a block device.

stats.isCharacterDevice()#
Added in: v0.1.10

Returnstrue if the<fs.Stats> object describes a character device.

stats.isDirectory()#
Added in: v0.1.10

Returnstrue if the<fs.Stats> object describes a file system directory.

If the<fs.Stats> object was obtained from callingfs.lstat() on asymbolic link which resolves to a directory, this method will returnfalse.This is becausefs.lstat() returns informationabout a symbolic link itself and not the path it resolves to.

stats.isFIFO()#
Added in: v0.1.10

Returnstrue if the<fs.Stats> object describes a first-in-first-out (FIFO)pipe.

stats.isFile()#
Added in: v0.1.10

Returnstrue if the<fs.Stats> object describes a regular file.

stats.isSocket()#
Added in: v0.1.10

Returnstrue if the<fs.Stats> object describes a socket.

stats.isSymbolicLink()#
Added in: v0.1.10

Returnstrue if the<fs.Stats> object describes a symbolic link.

This method is only valid when usingfs.lstat().

stats.dev#

The numeric identifier of the device containing the file.

stats.ino#

The file system specific "Inode" number for the file.

stats.mode#

A bit-field describing the file type and mode.

stats.nlink#

The number of hard-links that exist for the file.

stats.uid#

The numeric user identifier of the user that owns the file (POSIX).

stats.gid#

The numeric group identifier of the group that owns the file (POSIX).

stats.rdev#

A numeric device identifier if the file represents a device.

stats.size#

The size of the file in bytes.

If the underlying file system does not support getting the size of the file,this will be0.

stats.blksize#

The file system block size for i/o operations.

stats.blocks#

The number of blocks allocated for this file.

stats.atimeMs#
Added in: v8.1.0

The timestamp indicating the last time this file was accessed expressed inmilliseconds since the POSIX Epoch.

stats.mtimeMs#
Added in: v8.1.0

The timestamp indicating the last time this file was modified expressed inmilliseconds since the POSIX Epoch.

stats.ctimeMs#
Added in: v8.1.0

The timestamp indicating the last time the file status was changed expressedin milliseconds since the POSIX Epoch.

stats.birthtimeMs#
Added in: v8.1.0

The timestamp indicating the creation time of this file expressed inmilliseconds since the POSIX Epoch.

stats.atimeNs#
Added in: v12.10.0

Only present whenbigint: true is passed into the method that generatesthe object.The timestamp indicating the last time this file was accessed expressed innanoseconds since the POSIX Epoch.

stats.mtimeNs#
Added in: v12.10.0

Only present whenbigint: true is passed into the method that generatesthe object.The timestamp indicating the last time this file was modified expressed innanoseconds since the POSIX Epoch.

stats.ctimeNs#
Added in: v12.10.0

Only present whenbigint: true is passed into the method that generatesthe object.The timestamp indicating the last time the file status was changed expressedin nanoseconds since the POSIX Epoch.

stats.birthtimeNs#
Added in: v12.10.0

Only present whenbigint: true is passed into the method that generatesthe object.The timestamp indicating the creation time of this file expressed innanoseconds since the POSIX Epoch.

stats.atime#
Added in: v0.11.13

The timestamp indicating the last time this file was accessed.

stats.mtime#
Added in: v0.11.13

The timestamp indicating the last time this file was modified.

stats.ctime#
Added in: v0.11.13

The timestamp indicating the last time the file status was changed.

stats.birthtime#
Added in: v0.11.13

The timestamp indicating the creation time of this file.

Stat time values#

TheatimeMs,mtimeMs,ctimeMs,birthtimeMs properties arenumeric values that hold the corresponding times in milliseconds. Theirprecision is platform specific. Whenbigint: true is passed into themethod that generates the object, the properties will bebigints,otherwise they will benumbers.

TheatimeNs,mtimeNs,ctimeNs,birthtimeNs properties arebigints that hold the corresponding times in nanoseconds. They areonly present whenbigint: true is passed into the method that generatesthe object. Their precision is platform specific.

atime,mtime,ctime, andbirthtime areDate object alternate representations of the various times. TheDate and number values are not connected. Assigning a new number value, ormutating theDate value, will not be reflected in the corresponding alternaterepresentation.

The times in the stat object have the following semantics:

  • atime "Access Time": Time when file data last accessed. Changedby themknod(2),utimes(2), andread(2) system calls.
  • mtime "Modified Time": Time when file data last modified.Changed by themknod(2),utimes(2), andwrite(2) system calls.
  • ctime "Change Time": Time when file status was last changed(inode data modification). Changed by thechmod(2),chown(2),link(2),mknod(2),rename(2),unlink(2),utimes(2),read(2), andwrite(2) system calls.
  • birthtime "Birth Time": Time of file creation. Set once when thefile is created. On file systems where birthtime is not available,this field may instead hold either thectime or1970-01-01T00:00Z (ie, Unix epoch timestamp0). This value may be greaterthanatime ormtime in this case. On Darwin and other FreeBSD variants,also set if theatime is explicitly set to an earlier value than the currentbirthtime using theutimes(2) system call.

Prior to Node.js 0.12, thectime held thebirthtime on Windows systems. Asof 0.12,ctime is not "creation time", and on Unix systems, it never was.

Class:fs.StatFs#

Added in: v19.6.0, v18.15.0

Provides information about a mounted file system.

Objects returned fromfs.statfs() and its synchronous counterpart are ofthis type. Ifbigint in theoptions passed to those methods istrue, thenumeric values will bebigint instead ofnumber.

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}
statfs.bavail#
Added in: v19.6.0, v18.15.0

Free blocks available to unprivileged users.

statfs.bfree#
Added in: v19.6.0, v18.15.0

Free blocks in file system.

statfs.blocks#
Added in: v19.6.0, v18.15.0

Total data blocks in file system.

statfs.bsize#
Added in: v19.6.0, v18.15.0

Optimal transfer block size.

statfs.ffree#
Added in: v19.6.0, v18.15.0

Free file nodes in file system.

statfs.files#
Added in: v19.6.0, v18.15.0

Total file nodes in file system.

statfs.type#
Added in: v19.6.0, v18.15.0

Type of file system.

Class:fs.Utf8Stream#

Added in: v24.6.0

Stability: 1 - Experimental

An optimized UTF-8 stream writer that allows for flushing all the internalbuffering on demand. It handlesEAGAIN errors correctly, allowing forcustomization, for example, by dropping content if the disk is busy.

Event:'close'#

The'close' event is emitted when the stream is fully closed.

Event:'drain'#

The'drain' event is emitted when the internal buffer has drained sufficientlyto allow continued writing.

Event:'drop'#

The'drop' event is emitted when to maximal length is reached and that datawill not be written. The data that was dropped is passed as the first argumentto the event handle.

Event:'error'#

The'error' event is emitted when an error occurs.

Event:'finish'#

The'finish' event is emitted when the stream has been ended and all data hasbeen flushed to the underlying file.

Event:'ready'#

The'ready' event is emitted when the stream is ready to accept writes.

Event:'write'#

The'write' event is emitted when a write operation has completed. The numberof bytes written is passed as the first argument to the event handler.

new fs.Utf8Stream([options])#
  • options<Object>
    • append:<boolean> Appends writes to dest file instead of truncating it.Default:true.
    • contentMode:<string> Which type of data you can send to the writefunction, supported values are'utf8' or'buffer'.Default:'utf8'.
    • dest:<string> A path to a file to be written to (mode controlled by theappend option).
    • fd:<number> A file descriptor, something that is returned byfs.open()orfs.openSync().
    • fs:<Object> An object that has the same API as thefs module, usefulfor mocking, testing, or customizing the behavior of the stream.
    • fsync:<boolean> Perform afs.fsyncSync() every time a write iscompleted.
    • maxLength:<number> The maximum length of the internal buffer. If a writeoperation would cause the buffer to exceedmaxLength, the data written isdropped and a drop event is emitted with the dropped data
    • maxWrite:<number> The maximum number of bytes that can be written;Default:16384
    • minLength:<number> The minimum length of the internal buffer that isrequired to be full before flushing.
    • mkdir:<boolean> Ensure directory fordest file exists when true.Default:false.
    • mode:<number> |<string> Specify the creating file mode (seefs.open()).
    • periodicFlush:<number> Calls flush everyperiodicFlush milliseconds.
    • retryEAGAIN<Function> A function that will be called whenwrite(),writeSync(), orflushSync() encounters anEAGAIN orEBUSY error.If the return value istrue the operation will be retried, otherwise itwill bubble the error. Theerr is the error that caused this function tobe called,writeBufferLen is the length of the buffer that was written,andremainingBufferLen is the length of the remaining buffer that thestream did not try to write.
    • sync:<boolean> Perform writes synchronously.
utf8Stream.append#
  • <boolean> Whether the stream is appending to the file or truncating it.
utf8Stream.contentMode#
  • <string> The type of data that can be written to the stream. Supportedvalues are'utf8' or'buffer'.Default:'utf8'.
utf8Stream.destroy()#

Close the stream immediately, without flushing the internal buffer.

utf8Stream.end()#

Close the stream gracefully, flushing the internal buffer before closing.

utf8Stream.fd#
  • <number> The file descriptor that is being written to.
utf8Stream.file#
  • <string> The file that is being written to.
utf8Stream.flush(callback)#

Writes the current buffer to the file if a write was not in progress. Donothing ifminLength is zero or if it is already writing.

utf8Stream.flushSync()#

Flushes the buffered data synchronously. This is a costly operation.

utf8Stream.fsync#
  • <boolean> Whether the stream is performing afs.fsyncSync() after everywrite operation.
utf8Stream.maxLength#
  • <number> The maximum length of the internal buffer. If a writeoperation would cause the buffer to exceedmaxLength, the data written isdropped and a drop event is emitted with the dropped data.
utf8Stream.minLength#
  • <number> The minimum length of the internal buffer that is required to befull before flushing.
utf8Stream.mkdir#
  • <boolean> Whether the stream should ensure that the directory for thedest file exists. Iftrue, it will create the directory if it does notexist.Default:false.
utf8Stream.mode#
utf8Stream.periodicFlush#
  • <number> The number of milliseconds between flushes. If set to0, noperiodic flushes will be performed.
utf8Stream.reopen(file)#

Reopen the file in place, useful for log rotation.

utf8Stream.sync#
  • <boolean> Whether the stream is writing synchronously or asynchronously.
utf8Stream.write(data)#

When theoptions.contentMode is set to'utf8' when the stream is created,thedata argument must be a string. If thecontentMode is set to'buffer',thedata argument must be a<Buffer>.

utf8Stream.writing#
  • <boolean> Whether the stream is currently writing data to the file.
utf8Stream[Symbol.dispose]()#

Callsutf8Stream.destroy().

Class:fs.WriteStream#

Added in: v0.1.93

Instances of<fs.WriteStream> are created and returned using thefs.createWriteStream() function.

Event:'close'#
Added in: v0.1.93

Emitted when the<fs.WriteStream>'s underlying file descriptor has been closed.

Event:'open'#
Added in: v0.1.93

Emitted when the<fs.WriteStream>'s file is opened.

Event:'ready'#
Added in: v9.11.0

Emitted when the<fs.WriteStream> is ready to be used.

Fires immediately after'open'.

writeStream.bytesWritten#
Added in: v0.4.7

The number of bytes written so far. Does not include data that is still queuedfor writing.

writeStream.close([callback])#
Added in: v0.9.4

CloseswriteStream. Optionally accepts acallback that will be executed once thewriteStreamis closed.

writeStream.path#
Added in: v0.1.93

The path to the file the stream is writing to as specified in the firstargument tofs.createWriteStream(). Ifpath is passed as a string, thenwriteStream.path will be a string. Ifpath is passed as a<Buffer>, thenwriteStream.path will be a<Buffer>.

writeStream.pending#
Added in: v11.2.0

This property istrue if the underlying file has not been opened yet,i.e. before the'ready' event is emitted.

fs.constants#

Returns an object containing commonly used constants for file systemoperations.

FS constants#

The following constants are exported byfs.constants andfsPromises.constants.

Not every constant will be available on every operating system;this is especially important for Windows, where many of the POSIX specificdefinitions are not available.For portable applications it is recommended to check for their presencebefore use.

To use more than one constant, use the bitwise OR| operator.

Example:

import { open, constants }from'node:fs';const {O_RDWR,O_CREAT,O_EXCL,} = constants;open('/path/to/my/file',O_RDWR |O_CREAT |O_EXCL,(err, fd) => {// ...});
File access constants#

The following constants are meant for use as themode parameter passed tofsPromises.access(),fs.access(), andfs.accessSync().

ConstantDescription
F_OKFlag indicating that the file is visible to the calling process. This is useful for determining if a file exists, but says nothing aboutrwx permissions. Default if no mode is specified.
R_OKFlag indicating that the file can be read by the calling process.
W_OKFlag indicating that the file can be written by the calling process.
X_OKFlag indicating that the file can be executed by the calling process. This has no effect on Windows (will behave likefs.constants.F_OK).

The definitions are also available on Windows.

File copy constants#

The following constants are meant for use withfs.copyFile().

ConstantDescription
COPYFILE_EXCLIf present, the copy operation will fail with an error if the destination path already exists.
COPYFILE_FICLONEIf present, the copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
COPYFILE_FICLONE_FORCEIf present, the copy operation will attempt to create a copy-on-write reflink. If the underlying platform does not support copy-on-write, then the operation will fail with an error.

The definitions are also available on Windows.

File open constants#

The following constants are meant for use withfs.open().

ConstantDescription
O_RDONLYFlag indicating to open a file for read-only access.
O_WRONLYFlag indicating to open a file for write-only access.
O_RDWRFlag indicating to open a file for read-write access.
O_CREATFlag indicating to create the file if it does not already exist.
O_EXCLFlag indicating that opening a file should fail if theO_CREAT flag is set and the file already exists.
O_NOCTTYFlag indicating that if path identifies a terminal device, opening the path shall not cause that terminal to become the controlling terminal for the process (if the process does not already have one).
O_TRUNCFlag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero.
O_APPENDFlag indicating that data will be appended to the end of the file.
O_DIRECTORYFlag indicating that the open should fail if the path is not a directory.
O_NOATIMEFlag indicating reading accesses to the file system will no longer result in an update to theatime information associated with the file. This flag is available on Linux operating systems only.
O_NOFOLLOWFlag indicating that the open should fail if the path is a symbolic link.
O_SYNCFlag indicating that the file is opened for synchronized I/O with write operations waiting for file integrity.
O_DSYNCFlag indicating that the file is opened for synchronized I/O with write operations waiting for data integrity.
O_SYMLINKFlag indicating to open the symbolic link itself rather than the resource it is pointing to.
O_DIRECTWhen set, an attempt will be made to minimize caching effects of file I/O.
O_NONBLOCKFlag indicating to open the file in nonblocking mode when possible.
UV_FS_O_FILEMAPWhen set, a memory file mapping is used to access the file. This flag is available on Windows operating systems only. On other operating systems, this flag is ignored.

On Windows, onlyO_APPEND,O_CREAT,O_EXCL,O_RDONLY,O_RDWR,O_TRUNC,O_WRONLY, andUV_FS_O_FILEMAP are available.

File type constants#

The following constants are meant for use with the<fs.Stats> object'smode property for determining a file's type.

ConstantDescription
S_IFMTBit mask used to extract the file type code.
S_IFREGFile type constant for a regular file.
S_IFDIRFile type constant for a directory.
S_IFCHRFile type constant for a character-oriented device file.
S_IFBLKFile type constant for a block-oriented device file.
S_IFIFOFile type constant for a FIFO/pipe.
S_IFLNKFile type constant for a symbolic link.
S_IFSOCKFile type constant for a socket.

On Windows, onlyS_IFCHR,S_IFDIR,S_IFLNK,S_IFMT, andS_IFREG,are available.

File mode constants#

The following constants are meant for use with the<fs.Stats> object'smode property for determining the access permissions for a file.

ConstantDescription
S_IRWXUFile mode indicating readable, writable, and executable by owner.
S_IRUSRFile mode indicating readable by owner.
S_IWUSRFile mode indicating writable by owner.
S_IXUSRFile mode indicating executable by owner.
S_IRWXGFile mode indicating readable, writable, and executable by group.
S_IRGRPFile mode indicating readable by group.
S_IWGRPFile mode indicating writable by group.
S_IXGRPFile mode indicating executable by group.
S_IRWXOFile mode indicating readable, writable, and executable by others.
S_IROTHFile mode indicating readable by others.
S_IWOTHFile mode indicating writable by others.
S_IXOTHFile mode indicating executable by others.

On Windows, onlyS_IRUSR andS_IWUSR are available.

Notes#

Ordering of callback and promise-based operations#

Because they are executed asynchronously by the underlying thread pool,there is no guaranteed ordering when using either the callback orpromise-based methods.

For example, the following is prone to error because thefs.stat()operation might complete before thefs.rename() operation:

const fs =require('node:fs');fs.rename('/tmp/hello','/tmp/world',(err) => {if (err)throw err;console.log('renamed complete');});fs.stat('/tmp/world',(err, stats) => {if (err)throw err;console.log(`stats:${JSON.stringify(stats)}`);});

It is important to correctly order the operations by awaiting the resultsof one before invoking the other:

import { rename, stat }from'node:fs/promises';const oldPath ='/tmp/hello';const newPath ='/tmp/world';try {awaitrename(oldPath, newPath);const stats =awaitstat(newPath);console.log(`stats:${JSON.stringify(stats)}`);}catch (error) {console.error('there was an error:', error.message);}const { rename, stat } =require('node:fs/promises');(asyncfunction(oldPath, newPath) {try {awaitrename(oldPath, newPath);const stats =awaitstat(newPath);console.log(`stats:${JSON.stringify(stats)}`);  }catch (error) {console.error('there was an error:', error.message);  }})('/tmp/hello','/tmp/world');

Or, when using the callback APIs, move thefs.stat() call into the callbackof thefs.rename() operation:

import { rename, stat }from'node:fs';rename('/tmp/hello','/tmp/world',(err) => {if (err)throw err;stat('/tmp/world',(err, stats) => {if (err)throw err;console.log(`stats:${JSON.stringify(stats)}`);  });});const { rename, stat } =require('node:fs/promises');rename('/tmp/hello','/tmp/world',(err) => {if (err)throw err;stat('/tmp/world',(err, stats) => {if (err)throw err;console.log(`stats:${JSON.stringify(stats)}`);  });});

File paths#

Mostfs operations accept file paths that may be specified in the form ofa string, a<Buffer>, or a<URL> object using thefile: protocol.

String paths#

String paths are interpreted as UTF-8 character sequences identifyingthe absolute or relative filename. Relative paths will be resolved relativeto the current working directory as determined by callingprocess.cwd().

Example using an absolute path on POSIX:

import { open }from'node:fs/promises';let fd;try {  fd =awaitopen('/open/some/file.txt','r');// Do something with the file}finally {await fd?.close();}

Example using a relative path on POSIX (relative toprocess.cwd()):

import { open }from'node:fs/promises';let fd;try {  fd =awaitopen('file.txt','r');// Do something with the file}finally {await fd?.close();}
File URL paths#
Added in: v7.6.0

For mostnode:fs module functions, thepath orfilename argument may bepassed as a<URL> object using thefile: protocol.

import { readFileSync }from'node:fs';readFileSync(newURL('file:///tmp/hello'));

file: URLs are always absolute paths.

Platform-specific considerations#

On Windows,file:<URL>s with a host name convert to UNC paths, whilefile:<URL>s with drive letters convert to local absolute paths.file:<URL>swith no host name and no drive letter will result in an error:

import { readFileSync }from'node:fs';// On Windows :// - WHATWG file URLs with hostname convert to UNC path// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\filereadFileSync(newURL('file://hostname/p/a/t/h/file'));// - WHATWG file URLs with drive letters convert to absolute path// file:///C:/tmp/hello => C:\tmp\helloreadFileSync(newURL('file:///C:/tmp/hello'));// - WHATWG file URLs without hostname must have a drive lettersreadFileSync(newURL('file:///notdriveletter/p/a/t/h/file'));readFileSync(newURL('file:///c/p/a/t/h/file'));// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute

file:<URL>s with drive letters must use: as a separator just afterthe drive letter. Using another separator will result in an error.

On all other platforms,file:<URL>s with a host name are unsupported andwill result in an error:

import { readFileSync }from'node:fs';// On other platforms:// - WHATWG file URLs with hostname are unsupported// file://hostname/p/a/t/h/file => throw!readFileSync(newURL('file://hostname/p/a/t/h/file'));// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute// - WHATWG file URLs convert to absolute path// file:///tmp/hello => /tmp/helloreadFileSync(newURL('file:///tmp/hello'));

Afile:<URL> having encoded slash characters will result in an error on allplatforms:

import { readFileSync }from'node:fs';// On WindowsreadFileSync(newURL('file:///C:/p/a/t/h/%2F'));readFileSync(newURL('file:///C:/p/a/t/h/%2f'));/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\ or / characters */// On POSIXreadFileSync(newURL('file:///p/a/t/h/%2F'));readFileSync(newURL('file:///p/a/t/h/%2f'));/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded/ characters */

On Windows,file:<URL>s having encoded backslash will result in an error:

import { readFileSync }from'node:fs';// On WindowsreadFileSync(newURL('file:///C:/path/%5C'));readFileSync(newURL('file:///C:/path/%5c'));/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\ or / characters */
Buffer paths#

Paths specified using a<Buffer> are useful primarily on certain POSIXoperating systems that treat file paths as opaque byte sequences. On suchsystems, it is possible for a single file path to contain sub-sequences thatuse multiple character encodings. As with string paths,<Buffer> paths maybe relative or absolute:

Example using an absolute path on POSIX:

import { open }from'node:fs/promises';import {Buffer }from'node:buffer';let fd;try {  fd =awaitopen(Buffer.from('/open/some/file.txt'),'r');// Do something with the file}finally {await fd?.close();}
Per-drive working directories on Windows#

On Windows, Node.js follows the concept of per-drive working directory. Thisbehavior can be observed when using a drive path without a backslash. Forexamplefs.readdirSync('C:\\') can potentially return a different result thanfs.readdirSync('C:'). For more information, seethis MSDN page.

File descriptors#

On POSIX systems, for every process, the kernel maintains a table of currentlyopen files and resources. Each open file is assigned a simple numericidentifier called afile descriptor. At the system-level, all file systemoperations use these file descriptors to identify and track each specificfile. Windows systems use a different but conceptually similar mechanism fortracking resources. To simplify things for users, Node.js abstracts away thedifferences between operating systems and assigns all open files a numeric filedescriptor.

The callback-basedfs.open(), and synchronousfs.openSync() methods open afile and allocate a new file descriptor. Once allocated, the file descriptor maybe used to read data from, write data to, or request information about the file.

Operating systems limit the number of file descriptors that may be openat any given time so it is critical to close the descriptor when operationsare completed. Failure to do so will result in a memory leak that willeventually cause an application to crash.

import { open, close, fstat }from'node:fs';functioncloseFd(fd) {close(fd,(err) => {if (err)throw err;  });}open('/open/some/file.txt','r',(err, fd) => {if (err)throw err;try {fstat(fd,(err, stat) => {if (err) {closeFd(fd);throw err;      }// use statcloseFd(fd);    });  }catch (err) {closeFd(fd);throw err;  }});

The promise-based APIs use a<FileHandle> object in place of the numericfile descriptor. These objects are better managed by the system to ensurethat resources are not leaked. However, it is still required that they areclosed when operations are completed:

import { open }from'node:fs/promises';let file;try {  file =awaitopen('/open/some/file.txt','r');const stat =await file.stat();// use stat}finally {await file.close();}

Threadpool usage#

All callback and promise-based file system APIs (with the exception offs.FSWatcher()) use libuv's threadpool. This can have surprising and negativeperformance implications for some applications. See theUV_THREADPOOL_SIZE documentation for more information.

File system flags#

The following flags are available wherever theflag option takes astring.

  • 'a': Open file for appending.The file is created if it does not exist.

  • 'ax': Like'a' but fails if the path exists.

  • 'a+': Open file for reading and appending.The file is created if it does not exist.

  • 'ax+': Like'a+' but fails if the path exists.

  • 'as': Open file for appending in synchronous mode.The file is created if it does not exist.

  • 'as+': Open file for reading and appending in synchronous mode.The file is created if it does not exist.

  • 'r': Open file for reading.An exception occurs if the file does not exist.

  • 'rs': Open file for reading in synchronous mode.An exception occurs if the file does not exist.

  • 'r+': Open file for reading and writing.An exception occurs if the file does not exist.

  • 'rs+': Open file for reading and writing in synchronous mode. Instructsthe operating system to bypass the local file system cache.

    This is primarily useful for opening files on NFS mounts as it allowsskipping the potentially stale local cache. It has a very real impact onI/O performance so using this flag is not recommended unless it is needed.

    This doesn't turnfs.open() orfsPromises.open() into a synchronousblocking call. If synchronous operation is desired, something likefs.openSync() should be used.

  • 'w': Open file for writing.The file is created (if it does not exist) or truncated (if it exists).

  • 'wx': Like'w' but fails if the path exists.

  • 'w+': Open file for reading and writing.The file is created (if it does not exist) or truncated (if it exists).

  • 'wx+': Like'w+' but fails if the path exists.

flag can also be a number as documented byopen(2); commonly used constantsare available fromfs.constants. On Windows, flags are translated totheir equivalent ones where applicable, e.g.O_WRONLY toFILE_GENERIC_WRITE,orO_EXCL|O_CREAT toCREATE_NEW, as accepted byCreateFileW.

The exclusive flag'x' (O_EXCL flag inopen(2)) causes the operation toreturn an error if the path already exists. On POSIX, if the path is a symboliclink, usingO_EXCL returns an error even if the link is to a path that doesnot exist. The exclusive flag might not work with network file systems.

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 tothe end of the file.

Modifying a file rather than replacing it may require theflag option to beset to'r+' rather than the default'w'.

The behavior of some flags are platform-specific. As such, opening a directoryon macOS and Linux with the'a+' flag, as in the example below, will return anerror. In contrast, on Windows and FreeBSD, a file descriptor or aFileHandlewill be returned.

// macOS and Linuxfs.open('<directory>','a+',(err, fd) => {// => [Error: EISDIR: illegal operation on a directory, open <directory>]});// Windows and FreeBSDfs.open('<directory>','a+',(err, fd) => {// => null, <fd>});

On Windows, opening an existing hidden file using the'w' flag (eitherthroughfs.open(),fs.writeFile(), orfsPromises.open()) will fail withEPERM. Existing hidden files can be opened for writing with the'r+' flag.

A call tofs.ftruncate() orfilehandle.truncate() can be used to resetthe file contents.