File system#
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
Version | Changes |
---|---|
v14.0.0 | Exposed as |
v11.14.0, v10.17.0 | This API is no longer experimental. |
v10.1.0 | The API is accessible via |
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
#
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'
#
The'close'
event is emitted when the<FileHandle> has been closed and can nolonger be used.
filehandle.appendFile(data[, options])
#
History
Version | Changes |
---|---|
v21.1.0, v20.10.0 | The |
v15.14.0, v14.18.0 | The |
v14.0.0 | The |
v10.0.0 | Added in: v10.0.0 |
data
<string> |<Buffer> |<TypedArray> |<DataView> |<AsyncIterable> |<Iterable> |<Stream>options
<Object> |<string>encoding
<string> |<null>Default:'utf8'
signal
<AbortSignal> |<undefined> allows aborting an in-progress writeFile.Default:undefined
- Returns:<Promise> Fulfills with
undefined
upon success.
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.chown(uid, gid)
#
uid
<integer> The file's new owner's user id.gid
<integer> The file's new group's group id.- Returns:<Promise> Fulfills with
undefined
upon success.
Changes the ownership of the file. A wrapper forchown(2)
.
filehandle.close()
#
- Returns:<Promise> Fulfills with
undefined
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])
#
options
<Object>encoding
<string>Default:null
autoClose
<boolean>Default:true
emitClose
<boolean>Default:true
start
<integer>end
<integer>Default:Infinity
highWaterMark
<integer>Default:64 * 1024
signal
<AbortSignal> |<undefined>Default:undefined
- Returns:<fs.ReadStream>
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
Version | Changes |
---|---|
v21.0.0, v20.10.0 | The |
v16.11.0 | Added in: v16.11.0 |
options
<Object>- Returns:<fs.WriteStream>
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
open
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()
#
- Returns:<Promise> Fulfills with
undefined
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
#
- Type:<number> The numeric file descriptor managed by the<FileHandle> object.
filehandle.read(buffer, offset, length, position)
#
History
Version | Changes |
---|---|
v21.0.0 | Accepts bigint values as |
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:
bytesRead
<integer> The number of bytes readbuffer
<Buffer> |<TypedArray> |<DataView> A reference to the passed inbuffer
argument.
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
Version | Changes |
---|---|
v21.0.0 | Accepts bigint values as |
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:
bytesRead
<integer> The number of bytes readbuffer
<Buffer> |<TypedArray> |<DataView> A reference to the passed inbuffer
argument.
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
Version | Changes |
---|---|
v21.0.0 | Accepts bigint values as |
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:
bytesRead
<integer> The number of bytes readbuffer
<Buffer> |<TypedArray> |<DataView> A reference to the passed inbuffer
argument.
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
Version | Changes |
---|---|
v24.2.0 | Added the |
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 |
options
<Object>autoClose
<boolean> When true, causes the<FileHandle> to be closed when thestream is closed.Default:false
- Returns:<ReadableStream>
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)
#
options
<Object> |<string>encoding
<string> |<null>Default:null
signal
<AbortSignal> allows aborting an in-progress readFile
- Returns:<Promise> Fulfills upon a successful read with the contents of thefile. If no encoding is specified (using
options.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])
#
options
<Object>- Returns:<readline.InterfaceConstructor>
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])
#
buffers
<Buffer[]> |<TypedArray[]> |<DataView[]>position
<integer> |<null> The offset from the beginning of the file wherethe data should be read from. Ifposition
is not anumber
, the data willbe read from the current position.Default:null
- Returns:<Promise> Fulfills upon success an object containing two properties:
bytesRead
<integer> the number of bytes readbuffers
<Buffer[]> |<TypedArray[]> |<DataView[]> property containinga reference to thebuffers
input.
Read from a file and write to an array of<ArrayBufferView>s
filehandle.stat([options])
#
History
Version | Changes |
---|---|
v10.5.0 | Accepts an additional |
v10.0.0 | Added in: v10.0.0 |
options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.Stats> object should bebigint
.Default:false
.
- Returns:<Promise> Fulfills with an<fs.Stats> for the file.
filehandle.sync()
#
- Returns:<Promise> Fulfills with
undefined
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)
#
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)
#
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
Version | Changes |
---|---|
v14.0.0 | The |
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:
bytesWritten
<integer> the number of bytes writtenbuffer
<Buffer> |<TypedArray> |<DataView> a reference to thebuffer
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.write(buffer[, options])
#
buffer
<Buffer> |<TypedArray> |<DataView>options
<Object>- Returns:<Promise>
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
Version | Changes |
---|---|
v14.0.0 | The |
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:
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
Version | Changes |
---|---|
v15.14.0, v14.18.0 | The |
v14.0.0 | The |
v10.0.0 | Added in: v10.0.0 |
data
<string> |<Buffer> |<TypedArray> |<DataView> |<AsyncIterable> |<Iterable> |<Stream>options
<Object> |<string>encoding
<string> |<null> The expected character encoding whendata
is astring.Default:'utf8'
signal
<AbortSignal> |<undefined> allows aborting an in-progress writeFile.Default:undefined
- Returns:<Promise>
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])
#
buffers
<Buffer[]> |<TypedArray[]> |<DataView[]>position
<integer> |<null> The offset from the beginning of the file where thedata frombuffers
should be written. Ifposition
is not anumber
,the data will be written at the current position.Default:null
- Returns:<Promise>
Write an array of<ArrayBufferView>s to the file.
The promise is fulfilled with an object containing a two properties:
bytesWritten
<integer> the number of bytes writtenbuffers
<Buffer[]> |<TypedArray[]> |<DataView[]> a reference to thebuffers
input.
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
Version | Changes |
---|---|
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])
#
path
<string> |<Buffer> |<URL>mode
<integer>Default:fs.constants.F_OK
- Returns:<Promise> Fulfills with
undefined
upon success.
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_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 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
Version | Changes |
---|---|
v21.1.0, v20.10.0 | The |
v10.0.0 | Added in: v10.0.0 |
path
<string> |<Buffer> |<URL> |<FileHandle> filename or<FileHandle>data
<string> |<Buffer>options
<Object> |<string>- Returns:<Promise> Fulfills with
undefined
upon success.
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)
#
path
<string> |<Buffer> |<URL>mode
<string> |<integer>- Returns:<Promise> Fulfills with
undefined
upon success.
Changes the permissions of a file.
fsPromises.chown(path, uid, gid)
#
path
<string> |<Buffer> |<URL>uid
<integer>gid
<integer>- Returns:<Promise> Fulfills with
undefined
upon success.
Changes the ownership of a file.
fsPromises.copyFile(src, dest[, mode])
#
History
Version | Changes |
---|---|
v14.0.0 | Changed |
v10.0.0 | Added in: v10.0.0 |
src
<string> |<Buffer> |<URL> source filename to copydest
<string> |<Buffer> |<URL> destination filename of the copy operationmode
<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 ifdest
already 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 with
undefined
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
Version | Changes |
---|---|
v22.3.0 | This API is no longer experimental. |
v20.1.0, v18.17.0 | Accept an additional |
v17.6.0, v16.15.0 | Accepts an additional |
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 aPromise
that resolves totrue
orfalse
Default:undefined
.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 with
undefined
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
Version | Changes |
---|---|
v24.1.0 | Add support for |
v24.0.0 | Marking the API stable. |
v23.7.0, v22.14.0 | Add support for |
v22.2.0 | Add support for |
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)
#
Changes the permissions on a symbolic link.
This method is only implemented on macOS.
fsPromises.lchown(path, uid, gid)
#
History
Version | Changes |
---|---|
v10.6.0 | This API is no longer deprecated. |
v10.0.0 | Added in: v10.0.0 |
path
<string> |<Buffer> |<URL>uid
<integer>gid
<integer>- Returns:<Promise> Fulfills with
undefined
upon success.
Changes the ownership on a symbolic link.
fsPromises.lutimes(path, atime, mtime)
#
path
<string> |<Buffer> |<URL>atime
<number> |<string> |<Date>mtime
<number> |<string> |<Date>- Returns:<Promise> Fulfills with
undefined
upon success.
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)
#
existingPath
<string> |<Buffer> |<URL>newPath
<string> |<Buffer> |<URL>- Returns:<Promise> Fulfills with
undefined
upon success.
Creates a new link from theexistingPath
to thenewPath
. See the POSIXlink(2)
documentation for more detail.
fsPromises.lstat(path[, options])
#
History
Version | Changes |
---|---|
v10.5.0 | Accepts an additional |
v10.0.0 | Added in: v10.0.0 |
path
<string> |<Buffer> |<URL>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.Stats> object should bebigint
.Default:false
.
- Returns:<Promise> Fulfills with the<fs.Stats> object for the givensymbolic link
path
.
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])
#
path
<string> |<Buffer> |<URL>options
<Object> |<integer>- Returns:<Promise> Upon success, fulfills with
undefined
ifrecursive
isfalse
, or the first directory path created ifrecursive
istrue
.
Asynchronously creates a directory.
The optionaloptions
argument can be an integer specifyingmode
(permissionand sticky bits), or an object with amode
property and arecursive
property 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
Version | Changes |
---|---|
v20.6.0, v18.19.0 | The |
v16.5.0, v14.18.0 | The |
v10.0.0 | Added in: v10.0.0 |
prefix
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
- Returns:<Promise> Fulfills with a string containing the file system pathof the newly created temporary directory.
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])
#
prefix
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
- Returns:<Promise> Fulfills with a Promise for an async-disposable Object:
path
<string> The path of the created directory.remove
<AsyncFunction> A function which removes the created directory.[Symbol.asyncDispose]
<AsyncFunction> The same asremove
.
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
Version | Changes |
---|---|
v11.1.0 | The |
v10.0.0 | Added in: v10.0.0 |
path
<string> |<Buffer> |<URL>flags
<string> |<number> Seesupport of file systemflags
.Default:'r'
.mode
<string> |<integer> Sets the file mode (permission and sticky bits)if the file is created.Default:0o666
(readable and writable)- Returns:<Promise> Fulfills with a<FileHandle> object.
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
Version | Changes |
---|---|
v20.1.0, v18.17.0 | Added |
v13.1.0, v12.16.0 | The |
v12.12.0 | Added in: v12.12.0 |
path
<string> |<Buffer> |<URL>options
<Object>encoding
<string> |<null>Default:'utf8'
bufferSize
<number> Number of directory entries that are bufferedinternally when reading from the directory. Higher values lead to betterperformance but higher memory usage.Default:32
recursive
<boolean> ResolvedDir
will be an<AsyncIterable>containing all sub files and directories.Default:false
- Returns:<Promise> Fulfills with an<fs.Dir>.
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
Version | Changes |
---|---|
v20.1.0, v18.17.0 | Added |
v10.11.0 | New option |
v10.0.0 | Added in: v10.0.0 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>- 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
Version | Changes |
---|---|
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 |
path
<string> |<Buffer> |<URL> |<FileHandle> filename orFileHandle
options
<Object> |<string>encoding
<string> |<null>Default:null
flag
<string> Seesupport of file systemflags
.Default:'r'
.signal
<AbortSignal> allows aborting an in-progress readFile
- Returns:<Promise> Fulfills with the contents of the file.
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])
#
path
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
- Returns:<Promise> Fulfills with the
linkString
upon success.
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])
#
path
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
- Returns:<Promise> Fulfills with the resolved path upon success.
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)
#
oldPath
<string> |<Buffer> |<URL>newPath
<string> |<Buffer> |<URL>- Returns:<Promise> Fulfills with
undefined
upon success.
RenamesoldPath
tonewPath
.
fsPromises.rmdir(path[, options])
#
History
Version | Changes |
---|---|
v16.0.0 | Using |
v16.0.0 | Using |
v16.0.0 | The |
v14.14.0 | The |
v13.3.0, v12.16.0 | The |
v12.10.0 | The |
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 therecursive
option 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 with
undefined
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 anENOTDIR
error on POSIX.
To get a behavior similar to therm -rf
Unix command, usefsPromises.rm()
with options{ recursive: true, force: true }
.
fsPromises.rm(path[, options])
#
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 therecursive
option 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 with
undefined
upon success.
Removes files and directories (modeled on the standard POSIXrm
utility).
fsPromises.stat(path[, options])
#
History
Version | Changes |
---|---|
v10.5.0 | Accepts an additional |
v10.0.0 | Added in: v10.0.0 |
path
<string> |<Buffer> |<URL>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.Stats> object should bebigint
.Default:false
.
- Returns:<Promise> Fulfills with the<fs.Stats> object for thegiven
path
.
fsPromises.statfs(path[, options])
#
path
<string> |<Buffer> |<URL>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.StatFs> object should bebigint
.Default:false
.
- Returns:<Promise> Fulfills with the<fs.StatFs> object for thegiven
path
.
fsPromises.symlink(target, path[, type])
#
History
Version | Changes |
---|---|
v19.0.0 | If the |
v10.0.0 | Added in: v10.0.0 |
target
<string> |<Buffer> |<URL>path
<string> |<Buffer> |<URL>type
<string> |<null>Default:null
- Returns:<Promise> Fulfills with
undefined
upon success.
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])
#
path
<string> |<Buffer> |<URL>len
<integer>Default:0
- Returns:<Promise> Fulfills with
undefined
upon success.
Truncates (shortens or extends the length) of the content atpath
tolen
bytes.
fsPromises.unlink(path)
#
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)
#
path
<string> |<Buffer> |<URL>atime
<number> |<string> |<Date>mtime
<number> |<string> |<Date>- Returns:<Promise> Fulfills with
undefined
upon success.
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,
Date
s, or anumeric string like'123456789.0'
. - If the value can not be converted to a number, or is
NaN
,Infinity
, or-Infinity
, anError
will be thrown.
fsPromises.watch(filename[, options])
#
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
, wherefilename
is 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
Version | Changes |
---|---|
v21.0.0, v20.10.0 | The |
v15.14.0, v14.18.0 | The |
v15.2.0, v14.17.0 | The options argument may include an AbortSignal to abort an ongoing writeFile request. |
v14.0.0 | The |
v10.0.0 | Added in: v10.0.0 |
file
<string> |<Buffer> |<URL> |<FileHandle> filename orFileHandle
data
<string> |<Buffer> |<TypedArray> |<DataView> |<AsyncIterable> |<Iterable> |<Stream>options
<Object> |<string>encoding
<string> |<null>Default:'utf8'
mode
<integer>Default:0o666
flag
<string> Seesupport of file systemflags
.Default:'w'
.flush
<boolean> If all data is successfully written to the file, andflush
istrue
,filehandle.sync()
is used to flush the data.Default:false
.signal
<AbortSignal> allows aborting an in-progress writeFile
- Returns:<Promise> Fulfills with
undefined
upon success.
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
#
- Type:<Object>
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
Version | Changes |
---|---|
v20.8.0 | The constants |
v18.0.0 | Passing an invalid callback to the |
v7.6.0 | The |
v6.3.0 | The constants like |
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_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
.
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
Version | Changes |
---|---|
v21.1.0, v20.10.0 | The |
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.0.0 | The |
v7.0.0 | The passed |
v5.0.0 | The |
v0.6.7 | Added in: v0.6.7 |
path
<string> |<Buffer> |<URL> |<number> filename or file descriptordata
<string> |<Buffer>options
<Object> |<string>callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
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:
Constant | Octal | Description |
---|---|---|
fs.constants.S_IRUSR | 0o400 | read by owner |
fs.constants.S_IWUSR | 0o200 | write by owner |
fs.constants.S_IXUSR | 0o100 | execute/search by owner |
fs.constants.S_IRGRP | 0o40 | read by group |
fs.constants.S_IWGRP | 0o20 | write by group |
fs.constants.S_IXGRP | 0o10 | execute/search by group |
fs.constants.S_IROTH | 0o4 | read by others |
fs.constants.S_IWOTH | 0o2 | write by others |
fs.constants.S_IXOTH | 0o1 | execute/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.
Number | Description |
---|---|
7 | read, write, and execute |
6 | read and write |
5 | read and execute |
4 | read only |
3 | write and execute |
2 | write only |
1 | execute only |
0 | no 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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v15.9.0, v14.17.0 | A default callback is now used if one is not provided. |
v10.0.0 | The |
v7.0.0 | The |
v0.0.2 | Added in: v0.0.2 |
fd
<integer>callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v14.0.0 | Changed |
v8.5.0 | Added in: v8.5.0 |
src
<string> |<Buffer> |<URL> source filename to copydest
<string> |<Buffer> |<URL> destination filename of the copy operationmode
<integer> modifiers for copy operation.Default:0
.callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v22.3.0 | This API is no longer experimental. |
v20.1.0, v18.17.0 | Accept an additional |
v18.0.0 | Passing an invalid callback to the |
v17.6.0, v16.15.0 | Accepts an additional |
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 aPromise
that resolves totrue
orfalse
Default:undefined
.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>err
<Error>
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
Version | Changes |
---|---|
v16.10.0 | The |
v16.10.0 | The |
v15.5.0 | Add support for |
v15.4.0 | The |
v14.0.0 | Change |
v13.6.0, v12.17.0 | The |
v12.10.0 | Enable |
v11.0.0 | Impose new restrictions on |
v7.6.0 | The |
v7.0.0 | The passed |
v2.3.0 | The passed |
v0.1.31 | Added in: v0.1.31 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>flags
<string> Seesupport of file systemflags
.Default:'r'
.encoding
<string>Default:null
fd
<integer> |<FileHandle>Default:null
mode
<integer>Default:0o666
autoClose
<boolean>Default:true
emitClose
<boolean>Default:true
start
<integer>end
<integer>Default:Infinity
highWaterMark
<integer>Default:64 * 1024
fs
<Object> |<null>Default:null
signal
<AbortSignal> |<null>Default:null
- Returns:<fs.ReadStream>
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-blockingfd
s 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 correspondingfs
implementations 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
Version | Changes |
---|---|
v21.0.0, v20.10.0 | The |
v16.10.0 | The |
v16.10.0 | The |
v15.5.0 | Add support for |
v15.4.0 | The |
v14.0.0 | Change |
v13.6.0, v12.17.0 | The |
v12.10.0 | Enable |
v7.6.0 | The |
v7.0.0 | The passed |
v5.5.0 | The |
v2.3.0 | The passed |
v0.1.31 | Added in: v0.1.31 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>flags
<string> Seesupport of file systemflags
.Default:'w'
.encoding
<string>Default:'utf8'
fd
<integer> |<FileHandle>Default:null
mode
<integer>Default:0o666
autoClose
<boolean>Default:true
emitClose
<boolean>Default:true
start
<integer>fs
<Object> |<null>Default:null
signal
<AbortSignal> |<null>Default:null
highWaterMark
<number>Default:16384
flush
<boolean> Iftrue
, the underlying file descriptor is flushedprior to closing it.Default:false
.
- Returns:<fs.WriteStream>
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 correspondingfs
implementations 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 forclose
is 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-blockingfd
sshould be passed to<net.Socket>.
Ifoptions
is a string, then it specifies the encoding.
fs.exists(path, callback)
#
History
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v7.6.0 | The |
v1.0.0 | Deprecated since: v1.0.0 |
v0.0.2 | Added in: v0.0.2 |
path
<string> |<Buffer> |<URL>callback
<Function>exists
<boolean>
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 anerr
parameter, 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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.0.0 | The |
v0.4.7 | Added in: v0.4.7 |
fd
<integer>mode
<string> |<integer>callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.0.0 | The |
v0.4.7 | Added in: v0.4.7 |
fd
<integer>uid
<integer>gid
<integer>callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.0.0 | The |
v0.1.96 | Added in: v0.1.96 |
fd
<integer>callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.5.0 | Accepts an additional |
v10.0.0 | The |
v7.0.0 | The |
v0.1.95 | Added in: v0.1.95 |
fd
<integer>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.Stats> object should bebigint
.Default:false
.
callback
<Function>err
<Error>stats
<fs.Stats>
Invokes the callback with the<fs.Stats> for the file descriptor.
See the POSIXfstat(2)
documentation for more detail.
fs.fsync(fd, callback)
#
History
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.0.0 | The |
v0.1.96 | Added in: v0.1.96 |
fd
<integer>callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.0.0 | The |
v0.8.6 | Added in: v0.8.6 |
fd
<integer>len
<integer>Default:0
callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.0.0 | The |
v4.1.0 | Numeric strings, |
v0.4.2 | Added in: v0.4.2 |
fd
<integer>atime
<number> |<string> |<Date>mtime
<number> |<string> |<Date>callback
<Function>err
<Error>
Change the file system timestamps of the object referenced by the supplied filedescriptor. Seefs.utimes()
.
fs.glob(pattern[, options], callback)
#
History
Version | Changes |
---|---|
v24.1.0 | Add support for |
v24.0.0 | Marking the API stable. |
v23.7.0, v22.14.0 | Add support for |
v22.2.0 | Add support for |
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>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v16.0.0 | The error returned may be an |
v10.0.0 | The |
v7.0.0 | The |
v0.4.7 | Deprecated since: v0.4.7 |
path
<string> |<Buffer> |<URL>mode
<integer>callback
<Function>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.6.0 | This API is no longer deprecated. |
v10.0.0 | The |
v7.0.0 | The |
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v14.5.0, v12.19.0 | Added in: v14.5.0, v12.19.0 |
path
<string> |<Buffer> |<URL>atime
<number> |<string> |<Date>mtime
<number> |<string> |<Date>callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.5.0 | Accepts an additional |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
v0.1.30 | Added in: v0.1.30 |
path
<string> |<Buffer> |<URL>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.Stats> object should bebigint
.Default:false
.
callback
<Function>err
<Error>stats
<fs.Stats>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v13.11.0, v12.17.0 | In |
v10.12.0 | The second argument can now be an |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
v0.1.8 | Added in: v0.1.8 |
path
<string> |<Buffer> |<URL>options
<Object> |<integer>callback
<Function>err
<Error>path
<string> |<undefined> Present only if a directory is created withrecursive
set totrue
.
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 arecursive
property 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
Version | Changes |
---|---|
v20.6.0, v18.19.0 | The |
v18.0.0 | Passing an invalid callback to the |
v16.5.0, v14.18.0 | The |
v10.0.0 | The |
v7.0.0 | The |
v6.2.1 | The |
v5.10.0 | Added in: v5.10.0 |
prefix
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
callback
<Function>
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
, theprefix
must 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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v11.1.0 | The |
v9.9.0 | The |
v7.6.0 | The |
v0.0.2 | Added in: v0.0.2 |
path
<string> |<Buffer> |<URL>flags
<string> |<number> Seesupport of file systemflags
.Default:'r'
.mode
<string> |<integer>Default:0o666
(readable and writable)callback
<Function>
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
Version | Changes |
---|---|
v24.0.0 | Marking the API stable. |
v19.8.0 | Added in: v19.8.0 |
path
<string> |<Buffer> |<URL>options
<Object>type
<string> An optional mime type for the blob.
- Returns:<Promise> Fulfills with a<Blob> upon success.
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
Version | Changes |
---|---|
v20.1.0, v18.17.0 | Added |
v18.0.0 | Passing an invalid callback to the |
v13.1.0, v12.16.0 | The |
v12.12.0 | Added in: v12.12.0 |
path
<string> |<Buffer> |<URL>options
<Object>callback
<Function>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.10.0 | The |
v7.4.0 | The |
v6.0.0 | The |
v0.0.2 | Added in: v0.0.2 |
fd
<integer>buffer
<Buffer> |<TypedArray> |<DataView> The buffer that the data will bewritten to.offset
<integer> The position inbuffer
to write the data to.length
<integer> The number of bytes to read.position
<integer> |<bigint> |<null> Specifies where to begin reading from in thefile. Ifposition
isnull
or-1
, data will be read from the currentfile position, and the file position will be updated. Ifposition
isa non-negative integer, the file position will be unchanged.callback
<Function>
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 specified
length
,bytesRead
will 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 the
bytesRead
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 network
filesystem
or 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 wherebytesRead
is 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
Version | Changes |
---|---|
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 |
fd
<integer>options
<Object>buffer
<Buffer> |<TypedArray> |<DataView>Default:Buffer.alloc(16384)
offset
<integer>Default:0
length
<integer>Default:buffer.byteLength - offset
position
<integer> |<bigint> |<null>Default:null
callback
<Function>
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)
#
fd
<integer>buffer
<Buffer> |<TypedArray> |<DataView> The buffer that the data will bewritten to.options
<Object>callback
<Function>
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
Version | Changes |
---|---|
v20.1.0, v18.17.0 | Added |
v18.0.0 | Passing an invalid callback to the |
v10.10.0 | New option |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
v6.0.0 | The |
v0.1.8 | Added in: v0.1.8 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>callback
<Function>err
<Error>files
<string[]> |<Buffer[]> |<fs.Dirent[]>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v16.0.0 | The error returned may be an |
v15.2.0, v14.17.0 | The options argument may include an AbortSignal to abort an ongoing readFile request. |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
v5.1.0 | The |
v5.0.0 | The |
v0.1.29 | Added in: v0.1.29 |
path
<string> |<Buffer> |<URL> |<integer> filename or file descriptoroptions
<Object> |<string>encoding
<string> |<null>Default:null
flag
<string> Seesupport of file systemflags
.Default:'r'
.signal
<AbortSignal> allows aborting an in-progress readFile
callback
<Function>err
<Error> |<AggregateError>data
<string> |<Buffer>
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#
- Any specified file descriptor has to support reading.
- If a file descriptor is specified as the
path
, it will not be closedautomatically. - 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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
v0.1.31 | Added in: v0.1.31 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
callback
<Function>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v13.13.0, v12.17.0 | Added in: v13.13.0, v12.17.0 |
fd
<integer>buffers
<ArrayBufferView[]>position
<integer> |<null>Default:null
callback
<Function>err
<Error>bytesRead
<integer>buffers
<ArrayBufferView[]>
Read from a file specified byfd
and write to an array ofArrayBufferView
susingreadv()
.
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v8.0.0 | Pipe/Socket resolve support was added. |
v7.6.0 | The |
v7.0.0 | The |
v6.4.0 | Calling |
v6.0.0 | The |
v0.1.31 | Added in: v0.1.31 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
callback
<Function>
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:
No case conversion is performed on case-insensitive file systems.
The maximum number of symbolic links is platform-independent and generally(much) higher than what the native
realpath(3)
implementation supports.
Thecallback
gets two arguments(err, resolvedPath)
. May useprocess.cwd
to 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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v9.2.0 | Added in: v9.2.0 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
callback
<Function>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v16.0.0 | Using |
v16.0.0 | Using |
v16.0.0 | The |
v14.14.0 | The |
v13.3.0, v12.16.0 | The |
v12.10.0 | The |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
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 therecursive
option 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>err
<Error>
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
Version | Changes |
---|---|
v17.3.0, v16.14.0 | The |
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 therecursive
option 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>err
<Error>
Asynchronously removes files and directories (modeled on the standard POSIXrm
utility). No arguments other than a possible exception are given to thecompletion callback.
fs.stat(path[, options], callback)
#
History
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.5.0 | Accepts an additional |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
v0.0.2 | Added in: v0.0.2 |
path
<string> |<Buffer> |<URL>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.Stats> object should bebigint
.Default:false
.
callback
<Function>err
<Error>stats
<fs.Stats>
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)
#
path
<string> |<Buffer> |<URL>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.StatFs> object should bebigint
.Default:false
.
callback
<Function>err
<Error>stats
<fs.StatFs>
Asynchronousstatfs(2)
. Returns information about the mounted file system whichcontainspath
. The callback gets two arguments(err, stats)
wherestats
is an<fs.StatFs> object.
In case of an error, theerr.code
will be one ofCommon System Errors.
fs.symlink(target, path[, type], callback)
#
History
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v12.0.0 | If the |
v7.6.0 | The |
v0.1.31 | Added in: v0.1.31 |
target
<string> |<Buffer> |<URL>path
<string> |<Buffer> |<URL>type
<string> |<null>Default:null
callback
<Function>err
<Error>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v16.0.0 | The error returned may be an |
v10.0.0 | The |
v7.0.0 | The |
v0.8.6 | Added in: v0.8.6 |
path
<string> |<Buffer> |<URL>len
<integer>Default:0
callback
<Function>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v7.6.0 | The |
v7.0.0 | The |
v0.0.2 | Added in: v0.0.2 |
path
<string> |<Buffer> |<URL>callback
<Function>err
<Error>
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])
#
filename
<string> |<Buffer> |<URL>listener
<Function> Optional, a listener previously attached usingfs.watchFile()
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v10.0.0 | The |
v8.0.0 |
|
v7.6.0 | The |
v7.0.0 | The |
v4.1.0 | Numeric strings, |
v0.4.2 | Added in: v0.4.2 |
path
<string> |<Buffer> |<URL>atime
<number> |<string> |<Date>mtime
<number> |<string> |<Date>callback
<Function>err
<Error>
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,
Date
s, or a numeric string like'123456789.0'
. - If the value can not be converted to a number, or is
NaN
,Infinity
, or-Infinity
, anError
will be thrown.
fs.watch(filename[, options][, listener])
#
History
Version | Changes |
---|---|
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 | The |
v7.0.0 | The passed |
v0.5.10 | Added in: v0.5.10 |
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> allows closing the watcher with an AbortSignal.
listener
<Function> |<undefined>Default:undefined
- Returns:<fs.FSWatcher>
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)
.eventType
is 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 uses
inotify(7)
. - On BSD systems, this uses
kqueue(2)
. - On macOS, this uses
kqueue(2)
for files andFSEvents
fordirectories. - On SunOS systems (including Solaris and SmartOS), this uses
event ports
. - On Windows systems, this feature depends on
ReadDirectoryChangesW
. - On AIX systems, this feature depends on
AHAFS
, 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
Version | Changes |
---|---|
v10.5.0 | The |
v7.6.0 | The |
v0.1.31 | Added in: v0.1.31 |
filename
<string> |<Buffer> |<URL>options
<Object>listener
<Function>current
<fs.Stats>previous
<fs.Stats>
- Returns:<fs.StatWatcher>
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 asBigInt
s.
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v14.0.0 | The |
v10.10.0 | The |
v10.0.0 | The |
v7.4.0 | The |
v7.2.0 | The |
v7.0.0 | The |
v0.0.2 | Added in: v0.0.2 |
fd
<integer>buffer
<Buffer> |<TypedArray> |<DataView>offset
<integer>Default:0
length
<integer>Default:buffer.byteLength - offset
position
<integer> |<null>Default:null
callback
<Function>err
<Error>bytesWritten
<integer>buffer
<Buffer> |<TypedArray> |<DataView>
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)
#
fd
<integer>buffer
<Buffer> |<TypedArray> |<DataView>options
<Object>callback
<Function>err
<Error>bytesWritten
<integer>buffer
<Buffer> |<TypedArray> |<DataView>
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
Version | Changes |
---|---|
v19.0.0 | Passing to the |
v17.8.0 | Passing to the |
v14.12.0 | The |
v14.0.0 | The |
v10.0.0 | The |
v7.2.0 | The |
v7.0.0 | The |
v0.11.5 | Added in: v0.11.5 |
fd
<integer>string
<string>position
<integer> |<null>Default:null
encoding
<string>Default:'utf8'
callback
<Function>
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)
wherewritten
specifies 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 == 1
orstdout
) 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
Version | Changes |
---|---|
v21.0.0, v20.10.0 | The |
v19.0.0 | Passing to the |
v18.0.0 | Passing an invalid callback to the |
v17.8.0 | Passing to the |
v16.0.0 | The error returned may be an |
v15.2.0, v14.17.0 | The options argument may include an AbortSignal to abort an ongoing writeFile request. |
v14.12.0 | The |
v14.0.0 | The |
v10.10.0 | The |
v10.0.0 | The |
v7.4.0 | The |
v7.0.0 | The |
v5.0.0 | The |
v0.1.29 | Added in: v0.1.29 |
file
<string> |<Buffer> |<URL> |<integer> filename or file descriptordata
<string> |<Buffer> |<TypedArray> |<DataView>options
<Object> |<string>encoding
<string> |<null>Default:'utf8'
mode
<integer>Default:0o666
flag
<string> Seesupport of file systemflags
.Default:'w'
.flush
<boolean> If all data is successfully written to the file, andflush
istrue
,fs.fsync()
is used to flush the data.Default:false
.signal
<AbortSignal> allows aborting an in-progress writeFile
callback
<Function>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v12.9.0 | Added in: v12.9.0 |
fd
<integer>buffers
<ArrayBufferView[]>position
<integer> |<null>Default:null
callback
<Function>err
<Error>bytesWritten
<integer>buffers
<ArrayBufferView[]>
Write an array ofArrayBufferView
s 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
Version | Changes |
---|---|
v7.6.0 | The |
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
Version | Changes |
---|---|
v21.1.0, v20.10.0 | The |
v7.0.0 | The passed |
v5.0.0 | The |
v0.6.7 | Added in: v0.6.7 |
path
<string> |<Buffer> |<URL> |<number> filename or file descriptordata
<string> |<Buffer>options
<Object> |<string>
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
Version | Changes |
---|---|
v7.6.0 | The |
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
Version | Changes |
---|---|
v7.6.0 | The |
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)
#
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
Version | Changes |
---|---|
v14.0.0 | Changed |
v8.5.0 | Added in: v8.5.0 |
src
<string> |<Buffer> |<URL> source filename to copydest
<string> |<Buffer> |<URL> destination filename of the copy operationmode
<integer> modifiers for copy operation.Default: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
Version | Changes |
---|---|
v22.3.0 | This API is no longer experimental. |
v20.1.0, v18.17.0 | Accept an additional |
v17.6.0, v16.15.0 | Accepts an additional |
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
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
Version | Changes |
---|---|
v7.6.0 | The |
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. Thecallback
parameter 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)
#
Sets the permissions on the file. Returnsundefined
.
See the POSIXfchmod(2)
documentation for more detail.
fs.fchownSync(fd, uid, gid)
#
fd
<integer>uid
<integer> The file's new owner's user id.gid
<integer> The file's new group's group id.
Sets the owner of the file. Returnsundefined
.
See the POSIXfchown(2)
documentation for more detail.
fs.fdatasyncSync(fd)
#
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
Version | Changes |
---|---|
v10.5.0 | Accepts an additional |
v0.1.95 | Added in: v0.1.95 |
fd
<integer>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.Stats> object should bebigint
.Default:false
.
- Returns:<fs.Stats>
Retrieves the<fs.Stats> for the file descriptor.
See the POSIXfstat(2)
documentation for more detail.
fs.fsyncSync(fd)
#
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])
#
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
Version | Changes |
---|---|
v4.1.0 | Numeric strings, |
v0.4.2 | Added in: v0.4.2 |
Synchronous version offs.futimes()
. Returnsundefined
.
fs.globSync(pattern[, options])
#
History
Version | Changes |
---|---|
v24.1.0 | Add support for |
v24.0.0 | Marking the API stable. |
v23.7.0, v22.14.0 | Add support for |
v22.2.0 | Add support for |
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)
#
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
Version | Changes |
---|---|
v10.6.0 | This API is no longer deprecated. |
v0.4.7 | Documentation-only deprecation. |
path
<string> |<Buffer> |<URL>uid
<integer> The file's new owner's user id.gid
<integer> The file's new group's group id.
Set the owner for the path. Returnsundefined
.
See the POSIXlchown(2)
documentation for more details.
fs.lutimesSync(path, atime, mtime)
#
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
Version | Changes |
---|---|
v7.6.0 | The |
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
Version | Changes |
---|---|
v15.3.0, v14.17.0 | Accepts a |
v10.5.0 | Accepts an additional |
v7.6.0 | The |
v0.1.30 | Added in: v0.1.30 |
path
<string> |<Buffer> |<URL>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.Stats> object should bebigint
.Default:false
.throwIfNoEntry
<boolean> Whether an exception will be thrownif no file system entry exists, rather than returningundefined
.Default:true
.
- Returns:<fs.Stats>
Retrieves the<fs.Stats> for the symbolic link referred to bypath
.
See the POSIXlstat(2)
documentation for more details.
fs.mkdirSync(path[, options])
#
History
Version | Changes |
---|---|
v13.11.0, v12.17.0 | In |
v10.12.0 | The second argument can now be an |
v7.6.0 | The |
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
Version | Changes |
---|---|
v20.6.0, v18.19.0 | The |
v16.5.0, v14.18.0 | The |
v5.10.0 | Added in: v5.10.0 |
prefix
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
- Returns:<string>
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])
#
prefix
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
- Returns:<Object> A disposable object:
path
<string> The path of the created directory.remove
<Function> A function which removes the created directory.[Symbol.dispose]
<Function> The same asremove
.
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
Version | Changes |
---|---|
v20.1.0, v18.17.0 | Added |
v13.1.0, v12.16.0 | The |
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
Version | Changes |
---|---|
v11.1.0 | The |
v9.9.0 | The |
v7.6.0 | The |
v0.1.21 | Added in: v0.1.21 |
path
<string> |<Buffer> |<URL>flags
<string> |<number>Default:'r'
.Seesupport of file systemflags
.mode
<string> |<integer>Default:0o666
- Returns:<number>
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
Version | Changes |
---|---|
v20.1.0, v18.17.0 | Added |
v10.10.0 | New option |
v7.6.0 | The |
v0.1.21 | Added in: v0.1.21 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>- Returns:<string[]> |<Buffer[]> |<fs.Dirent[]>
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
Version | Changes |
---|---|
v7.6.0 | The |
v5.0.0 | The |
v0.1.8 | Added in: v0.1.8 |
path
<string> |<Buffer> |<URL> |<integer> filename or file descriptoroptions
<Object> |<string>encoding
<string> |<null>Default:null
flag
<string> Seesupport of file systemflags
.Default:'r'
.
- Returns:<string> |<Buffer>
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
Version | Changes |
---|---|
v7.6.0 | The |
v0.1.31 | Added in: v0.1.31 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
- Returns:<string> |<Buffer>
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
Version | Changes |
---|---|
v10.10.0 | The |
v6.0.0 | The |
v0.1.21 | Added in: v0.1.21 |
fd
<integer>buffer
<Buffer> |<TypedArray> |<DataView>offset
<integer>length
<integer>position
<integer> |<bigint> |<null>Default:null
- Returns:<number>
Returns the number ofbytesRead
.
For detailed information, see the documentation of the asynchronous version ofthis API:fs.read()
.
fs.readSync(fd, buffer[, options])
#
History
Version | Changes |
---|---|
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 |
fd
<integer>buffer
<Buffer> |<TypedArray> |<DataView>options
<Object>- Returns:<number>
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])
#
fd
<integer>buffers
<ArrayBufferView[]>position
<integer> |<null>Default:null
- Returns:<number> The number of bytes read.
For detailed information, see the documentation of the asynchronous version ofthis API:fs.readv()
.
fs.realpathSync(path[, options])
#
History
Version | Changes |
---|---|
v8.0.0 | Pipe/Socket resolve support was added. |
v7.6.0 | The |
v6.4.0 | Calling |
v6.0.0 | The |
v0.1.31 | Added in: v0.1.31 |
path
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
- Returns:<string> |<Buffer>
Returns the resolved pathname.
For detailed information, see the documentation of the asynchronous version ofthis API:fs.realpath()
.
fs.realpathSync.native(path[, options])
#
path
<string> |<Buffer> |<URL>options
<string> |<Object>encoding
<string>Default:'utf8'
- Returns:<string> |<Buffer>
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
Version | Changes |
---|---|
v7.6.0 | The |
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
Version | Changes |
---|---|
v16.0.0 | Using |
v16.0.0 | Using |
v16.0.0 | The |
v14.14.0 | The |
v13.3.0, v12.16.0 | The |
v12.10.0 | The |
v7.6.0 | The |
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 therecursive
option 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
Version | Changes |
---|---|
v17.3.0, v16.14.0 | The |
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 therecursive
option 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 POSIXrm
utility). Returnsundefined
.
fs.statSync(path[, options])
#
History
Version | Changes |
---|---|
v15.3.0, v14.17.0 | Accepts a |
v10.5.0 | Accepts an additional |
v7.6.0 | The |
v0.1.21 | Added in: v0.1.21 |
path
<string> |<Buffer> |<URL>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.Stats> object should bebigint
.Default:false
.throwIfNoEntry
<boolean> Whether an exception will be thrownif no file system entry exists, rather than returningundefined
.Default:true
.
- Returns:<fs.Stats>
Retrieves the<fs.Stats> for the path.
fs.statfsSync(path[, options])
#
path
<string> |<Buffer> |<URL>options
<Object>bigint
<boolean> Whether the numeric values in the returned<fs.StatFs> object should bebigint
.Default:false
.
- Returns:<fs.StatFs>
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
Version | Changes |
---|---|
v12.0.0 | If the |
v7.6.0 | The |
v0.1.31 | Added in: v0.1.31 |
target
<string> |<Buffer> |<URL>path
<string> |<Buffer> |<URL>type
<string> |<null>Default:null
- Returns:
undefined
.
For detailed information, see the documentation of the asynchronous version ofthis API:fs.symlink()
.
fs.truncateSync(path[, len])
#
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
Version | Changes |
---|---|
v7.6.0 | The |
v0.1.21 | Added in: v0.1.21 |
Synchronousunlink(2)
. Returnsundefined
.
fs.utimesSync(path, atime, mtime)
#
History
Version | Changes |
---|---|
v8.0.0 |
|
v7.6.0 | The |
v4.1.0 | Numeric strings, |
v0.4.2 | Added in: v0.4.2 |
path
<string> |<Buffer> |<URL>atime
<number> |<string> |<Date>mtime
<number> |<string> |<Date>- Returns:
undefined
.
For detailed information, see the documentation of the asynchronous version ofthis API:fs.utimes()
.
fs.writeFileSync(file, data[, options])
#
History
Version | Changes |
---|---|
v21.0.0, v20.10.0 | The |
v19.0.0 | Passing to the |
v17.8.0 | Passing to the |
v14.12.0 | The |
v14.0.0 | The |
v10.10.0 | The |
v7.4.0 | The |
v5.0.0 | The |
v0.1.29 | Added in: v0.1.29 |
file
<string> |<Buffer> |<URL> |<integer> filename or file descriptordata
<string> |<Buffer> |<TypedArray> |<DataView>options
<Object> |<string>- Returns:
undefined
.
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
Version | Changes |
---|---|
v14.0.0 | The |
v10.10.0 | The |
v7.4.0 | The |
v7.2.0 | The |
v0.1.21 | Added in: v0.1.21 |
fd
<integer>buffer
<Buffer> |<TypedArray> |<DataView>offset
<integer>Default:0
length
<integer>Default:buffer.byteLength - offset
position
<integer> |<null>Default:null
- Returns:<number> The number of bytes written.
For detailed information, see the documentation of the asynchronous version ofthis API:fs.write(fd, buffer...)
.
fs.writeSync(fd, buffer[, options])
#
fd
<integer>buffer
<Buffer> |<TypedArray> |<DataView>options
<Object>- Returns:<number> The number of bytes written.
For detailed information, see the documentation of the asynchronous version ofthis API:fs.write(fd, buffer...)
.
fs.writeSync(fd, string[, position[, encoding]])
#
History
Version | Changes |
---|---|
v14.0.0 | The |
v7.2.0 | The |
v0.11.5 | Added in: v0.11.5 |
fd
<integer>string
<string>position
<integer> |<null>Default:null
encoding
<string>Default:'utf8'
- Returns:<number> The number of bytes written.
For detailed information, see the documentation of the asynchronous version ofthis API:fs.write(fd, string...)
.
fs.writevSync(fd, buffers[, position])
#
fd
<integer>buffers
<ArrayBufferView[]>position
<integer> |<null>Default:null
- Returns:<number> The number of bytes written.
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
#
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()
#
- Returns:<Promise>
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
Version | Changes |
---|---|
v18.0.0 | Passing an invalid callback to the |
v12.12.0 | Added in: v12.12.0 |
callback
<Function>err
<Error>
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()
#
Synchronously close the directory's underlying resource handle.Subsequent reads will result in errors.
dir.path
#
- Type:<string>
The read-only path of this directory as was provided tofs.opendir()
,fs.opendirSync()
, orfsPromises.opendir()
.
dir.read()
#
- Returns:<Promise> Fulfills with a<fs.Dirent> |<null>
Asynchronously read the next directory entry viareaddir(3)
as an<fs.Dirent>.
A promise is returned that will be fulfilled 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.read(callback)
#
callback
<Function>err
<Error>dirent
<fs.Dirent> |<null>
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()
#
- Returns:<fs.Dirent> |<null>
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]()
#
- Returns:<AsyncIterator> An AsyncIterator of<fs.Dirent>
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
Version | Changes |
---|---|
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
Version | Changes |
---|---|
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
#
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()
#
- Returns:<boolean>
Returnstrue
if the<fs.Dirent> object describes a block device.
dirent.isCharacterDevice()
#
- Returns:<boolean>
Returnstrue
if the<fs.Dirent> object describes a character device.
dirent.isDirectory()
#
- Returns:<boolean>
Returnstrue
if the<fs.Dirent> object describes a file systemdirectory.
dirent.isFIFO()
#
- Returns:<boolean>
Returnstrue
if the<fs.Dirent> object describes a first-in-first-out(FIFO) pipe.
dirent.isFile()
#
- Returns:<boolean>
Returnstrue
if the<fs.Dirent> object describes a regular file.
dirent.isSocket()
#
- Returns:<boolean>
Returnstrue
if the<fs.Dirent> object describes a socket.
dirent.isSymbolicLink()
#
- Returns:<boolean>
Returnstrue
if the<fs.Dirent> object describes a symbolic link.
dirent.name
#
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
Version | Changes |
---|---|
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 |
- Type:<string>
The path to the parent directory of the file this<fs.Dirent> object refers to.
Class:fs.FSWatcher
#
- Extends<EventEmitter>
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'
#
eventType
<string> The type of change event that has occurredfilename
<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'
#
Emitted when the watcher stops watching for changes. The closed<fs.FSWatcher> object is no longer usable in the event handler.
Event:'error'
#
error
<Error>
Emitted when an error occurs while watching the file. The errored<fs.FSWatcher> object is no longer usable in the event handler.
watcher.close()
#
Stop watching for changes on the given<fs.FSWatcher>. Once stopped, the<fs.FSWatcher> object is no longer usable.
watcher.ref()
#
- Returns:<fs.FSWatcher>
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()
#
- Returns:<fs.FSWatcher>
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
#
- Extends<EventEmitter>
A successful call tofs.watchFile()
method will return a new<fs.StatWatcher>object.
watcher.ref()
#
- Returns:<fs.StatWatcher>
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()
#
- Returns:<fs.StatWatcher>
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
#
- Extends:<stream.Readable>
Instances of<fs.ReadStream> are created and returned using thefs.createReadStream()
function.
Event:'close'
#
Emitted when the<fs.ReadStream>'s underlying file descriptor has been closed.
Event:'open'
#
fd
<integer> Integer file descriptor used by the<fs.ReadStream>.
Emitted when the<fs.ReadStream>'s file descriptor has been opened.
Event:'ready'
#
Emitted when the<fs.ReadStream> is ready to be used.
Fires immediately after'open'
.
readStream.path
#
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
.
Class:fs.Stats
#
History
Version | Changes |
---|---|
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()
#
- Returns:<boolean>
Returnstrue
if the<fs.Stats> object describes a block device.
stats.isCharacterDevice()
#
- Returns:<boolean>
Returnstrue
if the<fs.Stats> object describes a character device.
stats.isDirectory()
#
- Returns:<boolean>
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()
#
- Returns:<boolean>
Returnstrue
if the<fs.Stats> object describes a first-in-first-out (FIFO)pipe.
stats.isFile()
#
- Returns:<boolean>
Returnstrue
if the<fs.Stats> object describes a regular file.
stats.isSocket()
#
- Returns:<boolean>
Returnstrue
if the<fs.Stats> object describes a socket.
stats.isSymbolicLink()
#
- Returns:<boolean>
Returnstrue
if the<fs.Stats> object describes a symbolic link.
This method is only valid when usingfs.lstat()
.
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.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.atimeMs
#
The timestamp indicating the last time this file was accessed expressed inmilliseconds since the POSIX Epoch.
stats.mtimeMs
#
The timestamp indicating the last time this file was modified expressed inmilliseconds since the POSIX Epoch.
stats.ctimeMs
#
The timestamp indicating the last time the file status was changed expressedin milliseconds since the POSIX Epoch.
stats.birthtimeMs
#
The timestamp indicating the creation time of this file expressed inmilliseconds since the POSIX Epoch.
stats.atimeNs
#
- Type:<bigint>
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
#
- Type:<bigint>
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
#
- Type:<bigint>
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
#
- Type:<bigint>
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
#
- Type:<Date>
The timestamp indicating the last time this file was accessed.
stats.mtime
#
- Type:<Date>
The timestamp indicating the last time this file was modified.
stats.ctime
#
- Type:<Date>
The timestamp indicating the last time the file status was changed.
stats.birthtime
#
- Type:<Date>
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
#
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}
Class:fs.Utf8Stream
#
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 datamaxWrite
:<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.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.flush(callback)
#
callback
<Function>
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 a
fs.fsyncSync()
after everywrite operation.
utf8Stream.maxLength
#
- <number> The maximum length of the internal buffer. If a writeoperation would cause the buffer to exceed
maxLength
, 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 the
dest
file exists. Iftrue
, it will create the directory if it does notexist.Default:false
.
utf8Stream.periodicFlush
#
- <number> The number of milliseconds between flushes. If set to
0
, noperiodic flushes will be performed.
utf8Stream.reopen(file)
#
file
:<string> |<Buffer> |<URL> A path to a file to be written to (modecontrolled by the append option).
Reopen the file in place, useful for log rotation.
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[Symbol.dispose]()
#
Callsutf8Stream.destroy()
.
Class:fs.WriteStream
#
- Extends<stream.Writable>
Instances of<fs.WriteStream> are created and returned using thefs.createWriteStream()
function.
Event:'close'
#
Emitted when the<fs.WriteStream>'s underlying file descriptor has been closed.
Event:'open'
#
fd
<integer> Integer file descriptor used by the<fs.WriteStream>.
Emitted when the<fs.WriteStream>'s file is opened.
Event:'ready'
#
Emitted when the<fs.WriteStream> is ready to be used.
Fires immediately after'open'
.
writeStream.bytesWritten
#
The number of bytes written so far. Does not include data that is still queuedfor writing.
writeStream.close([callback])
#
callback
<Function>err
<Error>
CloseswriteStream
. Optionally accepts acallback that will be executed once thewriteStream
is closed.
writeStream.path
#
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>.
fs.constants
#
- Type:<Object>
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()
.
Constant | Description |
---|---|
F_OK | Flag 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_OK | Flag indicating that the file can be read by the calling process. |
W_OK | Flag indicating that the file can be written by the calling process. |
X_OK | Flag 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()
.
Constant | Description |
---|---|
COPYFILE_EXCL | If present, the copy operation will fail with an error if the destination path already exists. |
COPYFILE_FICLONE | If 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_FORCE | If 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()
.
Constant | Description |
---|---|
O_RDONLY | Flag indicating to open a file for read-only access. |
O_WRONLY | Flag indicating to open a file for write-only access. |
O_RDWR | Flag indicating to open a file for read-write access. |
O_CREAT | Flag indicating to create the file if it does not already exist. |
O_EXCL | Flag indicating that opening a file should fail if theO_CREAT flag is set and the file already exists. |
O_NOCTTY | Flag 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_TRUNC | Flag 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_APPEND | Flag indicating that data will be appended to the end of the file. |
O_DIRECTORY | Flag indicating that the open should fail if the path is not a directory. |
O_NOATIME | Flag 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_NOFOLLOW | Flag indicating that the open should fail if the path is a symbolic link. |
O_SYNC | Flag indicating that the file is opened for synchronized I/O with write operations waiting for file integrity. |
O_DSYNC | Flag indicating that the file is opened for synchronized I/O with write operations waiting for data integrity. |
O_SYMLINK | Flag indicating to open the symbolic link itself rather than the resource it is pointing to. |
O_DIRECT | When set, an attempt will be made to minimize caching effects of file I/O. |
O_NONBLOCK | Flag indicating to open the file in nonblocking mode when possible. |
UV_FS_O_FILEMAP | When 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.
Constant | Description |
---|---|
S_IFMT | Bit mask used to extract the file type code. |
S_IFREG | File type constant for a regular file. |
S_IFDIR | File type constant for a directory. |
S_IFCHR | File type constant for a character-oriented device file. |
S_IFBLK | File type constant for a block-oriented device file. |
S_IFIFO | File type constant for a FIFO/pipe. |
S_IFLNK | File type constant for a symbolic link. |
S_IFSOCK | File 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.
Constant | Description |
---|---|
S_IRWXU | File mode indicating readable, writable, and executable by owner. |
S_IRUSR | File mode indicating readable by owner. |
S_IWUSR | File mode indicating writable by owner. |
S_IXUSR | File mode indicating executable by owner. |
S_IRWXG | File mode indicating readable, writable, and executable by group. |
S_IRGRP | File mode indicating readable by group. |
S_IWGRP | File mode indicating writable by group. |
S_IXGRP | File mode indicating executable by group. |
S_IRWXO | File mode indicating readable, writable, and executable by others. |
S_IROTH | File mode indicating readable by others. |
S_IWOTH | File mode indicating writable by others. |
S_IXOTH | File 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#
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 turn
fs.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 aFileHandle
will 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.