Source Code: lib/fs.js
The node:fs module enables interacting with the file system in a\nway modeled on standard POSIX functions.
node:fs
To use the promise-based APIs:
import * as fs from 'node:fs/promises';\n
const fs = require('node:fs/promises');\n
To use the callback and sync APIs:
import * as fs from 'node:fs';\n
const fs = require('node:fs');\n
All file system operations have synchronous, callback, and promise-based\nforms, and are accessible using both CommonJS syntax and ES6 Modules (ESM).
Promise-based operations return a promise that is fulfilled when the\nasynchronous operation is complete.
import { unlink } from 'node:fs/promises';\n\ntry {\n await unlink('/tmp/hello');\n console.log('successfully deleted /tmp/hello');\n} catch (error) {\n console.error('there was an error:', error.message);\n}\n
const { unlink } = require('node:fs/promises');\n\n(async function(path) {\n try {\n await unlink(path);\n console.log(`successfully deleted ${path}`);\n } catch (error) {\n console.error('there was an error:', error.message);\n }\n})('/tmp/hello');\n
The callback form takes a completion callback function as its last\nargument and invokes the operation asynchronously. The arguments passed to\nthe completion callback depend on the method, but the first argument is always\nreserved for an exception. If the operation is completed successfully, then\nthe first argument is null or undefined.
null
undefined
import { unlink } from 'node:fs';\n\nunlink('/tmp/hello', (err) => {\n if (err) throw err;\n console.log('successfully deleted /tmp/hello');\n});\n
const { unlink } = require('node:fs');\n\nunlink('/tmp/hello', (err) => {\n if (err) throw err;\n console.log('successfully deleted /tmp/hello');\n});\n
The callback-based versions of the node:fs module APIs are preferable over\nthe use of the promise APIs when maximal performance (both in terms of\nexecution time and memory allocation) is required.
The synchronous APIs block the Node.js event loop and further JavaScript\nexecution until the operation is complete. Exceptions are thrown immediately\nand can be handled using try…catch, or can be allowed to bubble up.
try…catch
import { unlinkSync } from 'node:fs';\n\ntry {\n unlinkSync('/tmp/hello');\n console.log('successfully deleted /tmp/hello');\n} catch (err) {\n // handle the error\n}\n
const { unlinkSync } = require('node:fs');\n\ntry {\n unlinkSync('/tmp/hello');\n console.log('successfully deleted /tmp/hello');\n} catch (err) {\n // handle the error\n}\n
The fs/promises API provides asynchronous file system methods that return\npromises.
fs/promises
The promise APIs use the underlying Node.js threadpool to perform file\nsystem operations off the event loop thread. These operations are not\nsynchronized or threadsafe. Care must be taken when performing multiple\nconcurrent modifications on the same file or data corruption may occur.
A <FileHandle> object is an object wrapper for a numeric file descriptor.
Instances of the <FileHandle> object are created by the fsPromises.open()\nmethod.
fsPromises.open()
All <FileHandle> objects are <EventEmitter>s.
If a <FileHandle> is not closed using the filehandle.close() method, it will\ntry to automatically close the file descriptor and emit a process warning,\nhelping to prevent memory leaks. Please do not rely on this behavior because\nit can be unreliable and the file may not be closed. Instead, always explicitly\nclose <FileHandle>s. Node.js may change this behavior in the future.
filehandle.close()
The 'close' event is emitted when the <FileHandle> has been closed and can no\nlonger be used.
'close'
Alias of filehandle.writeFile().
filehandle.writeFile()
When operating on file handles, the mode cannot be changed from what it was set\nto with fsPromises.open(). Therefore, this is equivalent to\nfilehandle.writeFile().
Modifies the permissions on the file. See chmod(2).
chmod(2)
Changes the ownership of the file. A wrapper for chown(2).
chown(2)
Closes the file handle after waiting for any pending operation on the handle to\ncomplete.
import { open } from 'node:fs/promises';\n\nlet filehandle;\ntry {\n filehandle = await open('thefile.txt', 'r');\n} finally {\n await filehandle?.close();\n}\n
Unlike the 16 KiB default highWaterMark for a <stream.Readable>, the stream\nreturned by this method has a default highWaterMark of 64 KiB.
highWaterMark
options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart counting at 0, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. If start is\nomitted or undefined, filehandle.createReadStream() reads sequentially from\nthe current file position. The encoding can be any one of those accepted by\n<Buffer>.
options
start
end
Number.MAX_SAFE_INTEGER
filehandle.createReadStream()
encoding
If the FileHandle points to a character device that only supports blocking\nreads (such as keyboard or sound card), read operations do not finish until data\nis available. This can prevent the process from exiting and the stream from\nclosing naturally.
FileHandle
By default, the stream will emit a 'close' event after it has been\ndestroyed. Set the emitClose option to false to change this behavior.
emitClose
false
import { open } from 'node:fs/promises';\n\nconst fd = await open('/dev/input/event0');\n// Create a stream from some character device.\nconst stream = fd.createReadStream();\nsetTimeout(() => {\n stream.close(); // This may not close the stream.\n // Artificially marking end-of-stream, as if the underlying resource had\n // indicated end-of-file by itself, allows the stream to close.\n // This does not cancel pending read operations, and if there is such an\n // operation, the process may still not be able to exit successfully\n // until it finishes.\n stream.push(null);\n stream.read(0);\n}, 100);\n
If autoClose is false, then the file descriptor won't be closed, even if\nthere's an error. It is the application's responsibility to close it and make\nsure there's no file descriptor leak. If autoClose is set to true (default\nbehavior), on 'error' or 'end' the file descriptor will be closed\nautomatically.
autoClose
'error'
'end'
An example to read the last 10 bytes of a file which is 100 bytes long:
import { open } from 'node:fs/promises';\n\nconst fd = await open('sample.txt');\nfd.createReadStream({ start: 90, end: 99 });\n
options may also include a start option to allow writing data at some\nposition past the beginning of the file, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than\nreplacing it may require the flags open option to be set to r+ rather than\nthe default r. The encoding can be any one of those accepted by <Buffer>.
flags
open
r+
r
If autoClose is set to true (default behavior) on 'error' or 'finish'\nthe file descriptor will be closed automatically. If autoClose is false,\nthen the file descriptor won't be closed, even if there's an error.\nIt is the application's responsibility to close it and make sure there's no\nfile descriptor leak.
'finish'
Forces all currently queued I/O operations associated with the file to the\noperating system's synchronized I/O completion state. Refer to the POSIX\nfdatasync(2) documentation for details.
fdatasync(2)
Unlike filehandle.sync this method does not flush modified metadata.
filehandle.sync
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 the\nnumber of bytes read is zero.
Asynchronously reads the entire contents of a file.
If options is a string, then it specifies the encoding.
The <FileHandle> has to support reading.
If one or more filehandle.read() calls are made on a file handle and then a\nfilehandle.readFile() call is made, the data will be read from the current\nposition till the end of the file. It doesn't always read from the beginning\nof the file.
filehandle.read()
filehandle.readFile()
Read from a file and write to an array of <ArrayBufferView>s
Request that all data for the open file descriptor is flushed to the storage\ndevice. The specific implementation is operating system and device specific.\nRefer to the POSIX fsync(2) documentation for more detail.
fsync(2)
Truncates the file.
If the file was larger than len bytes, only the first len bytes will be\nretained in the file.
len
The following example retains only the first four bytes of the file:
import { open } from 'node:fs/promises';\n\nlet filehandle = null;\ntry {\n filehandle = await open('temp.txt', 'r+');\n await filehandle.truncate(4);\n} finally {\n await filehandle?.close();\n}\n
If the file previously was shorter than len bytes, it is extended, and the\nextended part is filled with null bytes ('\\0'):
'\\0'
If len is negative then 0 will be used.
0
Change the file system timestamps of the object referenced by the <FileHandle>\nthen resolves the promise with no arguments upon success.
Write buffer to the file.
buffer
The promise is resolved with an object containing two properties:
bytesWritten
It is unsafe to use filehandle.write() multiple times on the same file\nwithout waiting for the promise to be resolved (or rejected). For this\nscenario, use filehandle.createWriteStream().
filehandle.write()
filehandle.createWriteStream()
On Linux, positional writes do not work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
Similar to the above filehandle.write function, this version takes an\noptional options object. If no options object is specified, it will\ndefault with the above values.
filehandle.write
Write string to the file. If string is not a string, the promise is\nrejected with an error.
string
Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string, a buffer, an <AsyncIterable>, or an <Iterable> object.\nThe promise is resolved with no arguments upon success.
data
The <FileHandle> has to support writing.
It is unsafe to use filehandle.writeFile() multiple times on the same file\nwithout waiting for the promise to be resolved (or rejected).
If one or more filehandle.write() calls are made on a file handle and then a\nfilehandle.writeFile() call is made, the data will be written from the\ncurrent position till the end of the file. It doesn't always write from the\nbeginning of the file.
Write an array of <ArrayBufferView>s to the file.
The promise is resolved with an object containing a two properties:
buffers
It is unsafe to call writev() multiple times on the same file without waiting\nfor the promise to be resolved (or rejected).
writev()
On Linux, positional writes don't work when the file is opened in append mode.\nThe kernel ignores the position argument and always appends the data to\nthe end of the file.
Tests a user's permissions for the file or directory specified by path.\nThe mode argument is an optional integer that specifies the accessibility\nchecks to be performed. mode should be either the value fs.constants.F_OK\nor a mask consisting of the bitwise OR of any of fs.constants.R_OK,\nfs.constants.W_OK, and fs.constants.X_OK (e.g.\nfs.constants.W_OK | fs.constants.R_OK). Check File access constants for\npossible values of mode.
path
mode
fs.constants.F_OK
fs.constants.R_OK
fs.constants.W_OK
fs.constants.X_OK
fs.constants.W_OK | fs.constants.R_OK
If the accessibility check is successful, the promise is resolved with no\nvalue. If any of the accessibility checks fail, the promise is rejected\nwith an <Error> object. The following example checks if the file\n/etc/passwd can be read and written by the current process.
/etc/passwd
import { access, constants } from 'node:fs/promises';\n\ntry {\n await access('/etc/passwd', constants.R_OK | constants.W_OK);\n console.log('can access');\n} catch {\n console.error('cannot access');\n}\n
Using fsPromises.access() to check for the accessibility of a file before\ncalling fsPromises.open() is not recommended. Doing so introduces a race\ncondition, since other processes may change the file's state between the two\ncalls. Instead, user code should open/read/write the file directly and handle\nthe error raised if the file is not accessible.
fsPromises.access()
Asynchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a <Buffer>.
The mode option only affects the newly created file. See fs.open()\nfor more details.
fs.open()
The path may be specified as a <FileHandle> that has been opened\nfor appending (using fsPromises.open()).
Changes the permissions of a file.
Changes the ownership of a file.
Asynchronously copies src to dest. By default, dest is overwritten if it\nalready exists.
src
dest
No guarantees are made about the atomicity of the copy operation. If an\nerror occurs after the destination file has been opened for writing, an attempt\nwill be made to remove the destination.
import { copyFile, constants } from 'node:fs/promises';\n\ntry {\n await copyFile('source.txt', 'destination.txt');\n console.log('source.txt was copied to destination.txt');\n} catch {\n console.log('The file could not be copied');\n}\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\ntry {\n await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL);\n console.log('source.txt was copied to destination.txt');\n} catch {\n console.log('The file could not be copied');\n}\n
Asynchronously copies the entire directory structure from src to dest,\nincluding subdirectories and files.
When copying a directory to another directory, globs are not supported and\nbehavior is similar to cp dir1/ dir2/.
cp dir1/ dir2/
Changes the permissions on a symbolic link.
This method is only implemented on macOS.
Changes the ownership on a symbolic link.
Changes the access and modification times of a file in the same way as\nfsPromises.utimes(), with the difference that if the path refers to a\nsymbolic link, then the link is not dereferenced: instead, the timestamps of\nthe symbolic link itself are changed.
fsPromises.utimes()
Creates a new link from the existingPath to the newPath. See the POSIX\nlink(2) documentation for more detail.
existingPath
newPath
link(2)
Equivalent to fsPromises.stat() unless path refers to a symbolic link,\nin which case the link itself is stat-ed, not the file that it refers to.\nRefer to the POSIX lstat(2) document for more detail.
fsPromises.stat()
lstat(2)
Asynchronously creates a directory.
The optional options argument can be an integer specifying mode (permission\nand sticky bits), or an object with a mode property and a recursive\nproperty indicating whether parent directories should be created. Calling\nfsPromises.mkdir() when path is a directory that exists results in a\nrejection only when recursive is false.
recursive
fsPromises.mkdir()
import { mkdir } from 'node:fs/promises';\n\ntry {\n const projectFolder = new URL('./test/project/', import.meta.url);\n const createDir = await mkdir(projectFolder, { recursive: true });\n\n console.log(`created ${createDir}`);\n} catch (err) {\n console.error(err.message);\n}\n
const { mkdir } = require('node:fs/promises');\nconst { resolve, join } = require('node:path');\n\nasync function makeDirectory() {\n const projectFolder = join(__dirname, 'test', 'project');\n const dirCreation = await mkdir(projectFolder, { recursive: true });\n\n console.log(dirCreation);\n return dirCreation;\n}\n\nmakeDirectory().catch(console.error);\n
Creates a unique temporary directory. A unique directory name is generated by\nappending six random characters to the end of the provided prefix. Due to\nplatform inconsistencies, avoid trailing X characters in prefix. Some\nplatforms, notably the BSDs, can return more than six random characters, and\nreplace trailing X characters in prefix with random characters.
prefix
X
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use.
import { mkdtemp } from 'node:fs/promises';\n\ntry {\n await mkdtemp(path.join(os.tmpdir(), 'foo-'));\n} catch (err) {\n console.error(err);\n}\n
The fsPromises.mkdtemp() method will append the six randomly selected\ncharacters directly to the prefix string. For instance, given a directory\n/tmp, if the intention is to create a temporary directory within /tmp, the\nprefix must end with a trailing platform-specific path separator\n(require('node:path').sep).
fsPromises.mkdtemp()
/tmp
require('node:path').sep
Opens a <FileHandle>.
Refer to the POSIX open(2) documentation for more detail.
open(2)
Some characters (< > : \" / \\ | ? *) are reserved under Windows as documented\nby Naming Files, Paths, and Namespaces. Under NTFS, if the filename contains\na colon, Node.js will open a file system stream, as described by\nthis MSDN page.
< > : \" / \\ | ? *
Asynchronously open a directory for iterative scanning. See the POSIX\nopendir(3) documentation for more detail.
opendir(3)
Creates an <fs.Dir>, which contains all further functions for reading from\nand cleaning up the directory.
The encoding option sets the encoding for the path while opening the\ndirectory and subsequent read operations.
Example using async iteration:
import { opendir } from 'node:fs/promises';\n\ntry {\n const dir = await opendir('./');\n for await (const dirent of dir)\n console.log(dirent.name);\n} catch (err) {\n console.error(err);\n}\n
When using the async iterator, the <fs.Dir> object will be automatically\nclosed after the iterator exits.
Reads the contents of a directory.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames. If the encoding is set to 'buffer', the filenames returned\nwill be passed as <Buffer> objects.
'buffer'
If options.withFileTypes is set to true, the resolved array will contain\n<fs.Dirent> objects.
options.withFileTypes
true
import { readdir } from 'node:fs/promises';\n\ntry {\n const files = await readdir(path);\n for (const file of files)\n console.log(file);\n} catch (err) {\n console.error(err);\n}\n
If no encoding is specified (using options.encoding), the data is returned\nas a <Buffer> object. Otherwise, the data will be a string.
options.encoding
When the path is a directory, the behavior of fsPromises.readFile() is\nplatform-specific. On macOS, Linux, and Windows, the promise will be rejected\nwith an error. On FreeBSD, a representation of the directory's contents will be\nreturned.
fsPromises.readFile()
It is possible to abort an ongoing readFile using an <AbortSignal>. If a\nrequest is aborted the promise returned is rejected with an AbortError:
readFile
AbortError
import { readFile } from 'node:fs/promises';\n\ntry {\n const controller = new AbortController();\n const { signal } = controller;\n const promise = readFile(fileName, { signal });\n\n // Abort the request before the promise settles.\n controller.abort();\n\n await promise;\n} catch (err) {\n // When a request is aborted - err is an AbortError\n console.error(err);\n}\n
Aborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.readFile performs.
fs.readFile
Any specified <FileHandle> has to support reading.
Reads the contents of the symbolic link referred to by path. See the POSIX\nreadlink(2) documentation for more detail. The promise is resolved with the\nlinkString upon success.
readlink(2)
linkString
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path returned. If the encoding is set to 'buffer', the link path\nreturned will be passed as a <Buffer> object.
Determines the actual location of path using the same semantics as the\nfs.realpath.native() function.
fs.realpath.native()
Only paths that can be converted to UTF8 strings are supported.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path. If the encoding is set to 'buffer', the path returned will be\npassed as a <Buffer> object.
On Linux, when Node.js is linked against musl libc, the procfs file system must\nbe mounted on /proc in order for this function to work. Glibc does not have\nthis restriction.
/proc
Renames oldPath to newPath.
oldPath
Removes the directory identified by path.
Using fsPromises.rmdir() on a file (not a directory) results in the\npromise being rejected with an ENOENT error on Windows and an ENOTDIR\nerror on POSIX.
fsPromises.rmdir()
ENOENT
ENOTDIR
To get a behavior similar to the rm -rf Unix command, use\nfsPromises.rm() with options { recursive: true, force: true }.
rm -rf
fsPromises.rm()
{ recursive: true, force: true }
Removes files and directories (modeled on the standard POSIX rm utility).
rm
Creates a symbolic link.
The type argument is only used on Windows platforms and can be one of 'dir',\n'file', or 'junction'. Windows junction points require the destination path\nto be absolute. When using 'junction', the target argument will\nautomatically be normalized to absolute path.
type
'dir'
'file'
'junction'
target
Truncates (shortens or extends the length) of the content at path to len\nbytes.
If path refers to a symbolic link, then the link is removed without affecting\nthe file or directory to which that link refers. If the path refers to a file\npath that is not a symbolic link, the file is deleted. See the POSIX unlink(2)\ndocumentation for more detail.
unlink(2)
Change the file system timestamps of the object referenced by path.
The atime and mtime arguments follow these rules:
atime
mtime
Date
'123456789.0'
NaN
Infinity
-Infinity
Error
Returns an async iterator that watches for changes on filename, where filename\nis either a file or a directory.
filename
const { watch } = require('node:fs/promises');\n\nconst ac = new AbortController();\nconst { signal } = ac;\nsetTimeout(() => ac.abort(), 10000);\n\n(async () => {\n try {\n const watcher = watch(__filename, { signal });\n for await (const event of watcher)\n console.log(event);\n } catch (err) {\n if (err.name === 'AbortError')\n return;\n throw err;\n }\n})();\n
On most platforms, 'rename' is emitted whenever a filename appears or\ndisappears in the directory.
'rename'
All the caveats for fs.watch() also apply to fsPromises.watch().
fs.watch()
fsPromises.watch()
Asynchronously writes data to a file, replacing the file if it already exists.\ndata can be a string, a buffer, an <AsyncIterable>, or an <Iterable> object.
The encoding option is ignored if data is a buffer.
Any specified <FileHandle> has to support writing.
It is unsafe to use fsPromises.writeFile() multiple times on the same file\nwithout waiting for the promise to be settled.
fsPromises.writeFile()
Similarly to fsPromises.readFile - fsPromises.writeFile is a convenience\nmethod that performs multiple write calls internally to write the buffer\npassed to it. For performance sensitive code consider using\nfs.createWriteStream() or filehandle.createWriteStream().
fsPromises.readFile
fsPromises.writeFile
write
fs.createWriteStream()
It is possible to use an <AbortSignal> to cancel an fsPromises.writeFile().\nCancelation is \"best effort\", and some amount of data is likely still\nto be written.
import { writeFile } from 'node:fs/promises';\nimport { Buffer } from 'node:buffer';\n\ntry {\n const controller = new AbortController();\n const { signal } = controller;\n const data = new Uint8Array(Buffer.from('Hello Node.js'));\n const promise = writeFile('message.txt', data, { signal });\n\n // Abort the request before the promise settles.\n controller.abort();\n\n await promise;\n} catch (err) {\n // When a request is aborted - err is an AbortError\n console.error(err);\n}\n
Aborting an ongoing request does not abort individual operating\nsystem requests but rather the internal buffering fs.writeFile performs.
fs.writeFile
Returns an object containing commonly used constants for file system\noperations. The object is the same as fs.constants. See FS constants\nfor more details.
fs.constants
The callback APIs perform all operations asynchronously, without blocking the\nevent loop, then invoke a callback function upon completion or error.
The callback APIs use the underlying Node.js threadpool to perform file\nsystem operations off the event loop thread. These operations are not\nsynchronized or threadsafe. Care must be taken when performing multiple\nconcurrent modifications on the same file or data corruption may occur.
The final argument, callback, is a callback function that is invoked with\na possible error argument. If any of the accessibility checks fail, the error\nargument will be an Error object. The following examples check if\npackage.json exists, and if it is readable or writable.
callback
package.json
import { access, constants } from 'node:fs';\n\nconst file = 'package.json';\n\n// Check if the file exists in the current directory.\naccess(file, constants.F_OK, (err) => {\n console.log(`${file} ${err ? 'does not exist' : 'exists'}`);\n});\n\n// Check if the file is readable.\naccess(file, constants.R_OK, (err) => {\n console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);\n});\n\n// Check if the file is writable.\naccess(file, constants.W_OK, (err) => {\n console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);\n});\n\n// Check if the file is readable and writable.\naccess(file, constants.R_OK | constants.W_OK, (err) => {\n console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`);\n});\n
Do not use fs.access() to check for the accessibility of a file before calling\nfs.open(), fs.readFile(), or fs.writeFile(). Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file is not accessible.
fs.access()
fs.readFile()
fs.writeFile()
write (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';\n\naccess('myfile', (err) => {\n if (!err) {\n console.error('myfile already exists');\n return;\n }\n\n open('myfile', 'wx', (err, fd) => {\n if (err) throw err;\n\n try {\n writeMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n });\n});\n
write (RECOMMENDED)
import { open, close } from 'node:fs';\n\nopen('myfile', 'wx', (err, fd) => {\n if (err) {\n if (err.code === 'EEXIST') {\n console.error('myfile already exists');\n return;\n }\n\n throw err;\n }\n\n try {\n writeMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n});\n
read (NOT RECOMMENDED)
import { access, open, close } from 'node:fs';\naccess('myfile', (err) => {\n if (err) {\n if (err.code === 'ENOENT') {\n console.error('myfile does not exist');\n return;\n }\n\n throw err;\n }\n\n open('myfile', 'r', (err, fd) => {\n if (err) throw err;\n\n try {\n readMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n });\n});\n
read (RECOMMENDED)
import { open, close } from 'node:fs';\n\nopen('myfile', 'r', (err, fd) => {\n if (err) {\n if (err.code === 'ENOENT') {\n console.error('myfile does not exist');\n return;\n }\n\n throw err;\n }\n\n try {\n readMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n});\n
The \"not recommended\" examples above check for accessibility and then use the\nfile; the \"recommended\" examples are better because they use the file directly\nand handle the error, if any.
In general, check for the accessibility of a file only if the file will not be\nused directly, for example when its accessibility is a signal from another\nprocess.
On Windows, access-control policies (ACLs) on a directory may limit access to\na file or directory. The fs.access() function, however, does not check the\nACL and therefore may report that a path is accessible even if the ACL restricts\nthe user from reading or writing to it.
import { appendFile } from 'node:fs';\n\nappendFile('message.txt', 'data to append', (err) => {\n if (err) throw err;\n console.log('The \"data to append\" was appended to file!');\n});\n
If options is a string, then it specifies the encoding:
import { appendFile } from 'node:fs';\n\nappendFile('message.txt', 'data to append', 'utf8', callback);\n
The path may be specified as a numeric file descriptor that has been opened\nfor appending (using fs.open() or fs.openSync()). The file descriptor will\nnot be closed automatically.
fs.openSync()
import { open, close, appendFile } from 'node:fs';\n\nfunction closeFd(fd) {\n close(fd, (err) => {\n if (err) throw err;\n });\n}\n\nopen('message.txt', 'a', (err, fd) => {\n if (err) throw err;\n\n try {\n appendFile(fd, 'data to append', 'utf8', (err) => {\n closeFd(fd);\n if (err) throw err;\n });\n } catch (err) {\n closeFd(fd);\n throw err;\n }\n});\n
Asynchronously changes the permissions of a file. No arguments other than a\npossible exception are given to the completion callback.
See the POSIX chmod(2) documentation for more detail.
import { chmod } from 'node:fs';\n\nchmod('my_file.txt', 0o775, (err) => {\n if (err) throw err;\n console.log('The permissions for file \"my_file.txt\" have been changed!');\n});\n
The mode argument used in both the fs.chmod() and fs.chmodSync()\nmethods is a numeric bitmask created using a logical OR of the following\nconstants:
fs.chmod()
fs.chmodSync()
fs.constants.S_IRUSR
0o400
fs.constants.S_IWUSR
0o200
fs.constants.S_IXUSR
0o100
fs.constants.S_IRGRP
0o40
fs.constants.S_IWGRP
0o20
fs.constants.S_IXGRP
0o10
fs.constants.S_IROTH
0o4
fs.constants.S_IWOTH
0o2
fs.constants.S_IXOTH
0o1
An easier method of constructing the mode is to use a sequence of three\noctal digits (e.g. 765). The left-most digit (7 in the example), specifies\nthe permissions for the file owner. The middle digit (6 in the example),\nspecifies permissions for the group. The right-most digit (5 in the example),\nspecifies the permissions for others.
765
7
6
5
4
3
2
1
For example, the octal value 0o765 means:
0o765
When using raw numbers where file modes are expected, any value larger than\n0o777 may result in platform-specific behaviors that are not supported to work\nconsistently. Therefore constants like S_ISVTX, S_ISGID, or S_ISUID are\nnot exposed in fs.constants.
0o777
S_ISVTX
S_ISGID
S_ISUID
Caveats: on Windows only the write permission can be changed, and the\ndistinction among the permissions of group, owner, or others is not\nimplemented.
Asynchronously changes owner and group of a file. No arguments other than a\npossible exception are given to the completion callback.
See the POSIX chown(2) documentation for more detail.
Closes the file descriptor. No arguments other than a possible exception are\ngiven to the completion callback.
Calling fs.close() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.
fs.close()
fd
fs
See the POSIX close(2) documentation for more detail.
close(2)
Asynchronously copies src to dest. By default, dest is overwritten if it\nalready exists. No arguments other than a possible exception are given to the\ncallback function. Node.js makes no guarantees about the atomicity of the copy\noperation. If an error occurs after the destination file has been opened for\nwriting, Node.js will attempt to remove the destination.
mode is an optional integer that specifies the behavior\nof the copy operation. It is possible to create a mask consisting of the bitwise\nOR of two or more values (e.g.\nfs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE).
fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE
fs.constants.COPYFILE_EXCL
fs.constants.COPYFILE_FICLONE
fs.constants.COPYFILE_FICLONE_FORCE
import { copyFile, constants } from 'node:fs';\n\nfunction callback(err) {\n if (err) throw err;\n console.log('source.txt was copied to destination.txt');\n}\n\n// destination.txt will be created or overwritten by default.\ncopyFile('source.txt', 'destination.txt', callback);\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\ncopyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);\n
options can include start and end values to read a range of bytes from\nthe file instead of the entire file. Both start and end are inclusive and\nstart counting at 0, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. If fd is specified and start is\nomitted or undefined, fs.createReadStream() reads sequentially from the\ncurrent file position. The encoding can be any one of those accepted by\n<Buffer>.
fs.createReadStream()
If fd is specified, ReadStream will ignore the path argument and will use\nthe specified file descriptor. This means that no 'open' event will be\nemitted. fd should be blocking; non-blocking fds should be passed to\n<net.Socket>.
ReadStream
'open'
If fd points to a character device that only supports blocking reads\n(such as keyboard or sound card), read operations do not finish until data is\navailable. This can prevent the process from exiting and the stream from\nclosing naturally.
By providing the fs option, it is possible to override the corresponding fs\nimplementations for open, read, and close. When providing the fs option,\nan override for read is required. If no fd is provided, an override for\nopen is also required. If autoClose is true, an override for close is\nalso required.
read
close
import { createReadStream } from 'node:fs';\n\n// Create a stream from some character device.\nconst stream = createReadStream('/dev/input/event0');\nsetTimeout(() => {\n stream.close(); // This may not close the stream.\n // Artificially marking end-of-stream, as if the underlying resource had\n // indicated end-of-file by itself, allows the stream to close.\n // This does not cancel pending read operations, and if there is such an\n // operation, the process may still not be able to exit successfully\n // until it finishes.\n stream.push(null);\n stream.read(0);\n}, 100);\n
mode sets the file mode (permission and sticky bits), but only if the\nfile was created.
import { createReadStream } from 'node:fs';\n\ncreateReadStream('sample.txt', { start: 90, end: 99 });\n
options may also include a start option to allow writing data at some\nposition past the beginning of the file, allowed values are in the\n[0, Number.MAX_SAFE_INTEGER] range. Modifying a file rather than\nreplacing it may require the flags option to be set to r+ rather than the\ndefault w. The encoding can be any one of those accepted by <Buffer>.
w
By providing the fs option it is possible to override the corresponding fs\nimplementations for open, write, writev, and close. Overriding write()\nwithout writev() can reduce performance as some optimizations (_writev())\nwill be disabled. When providing the fs option, overrides for at least one of\nwrite and writev are required. If no fd option is supplied, an override\nfor open is also required. If autoClose is true, an override for close\nis also required.
writev
write()
_writev()
Like <fs.ReadStream>, if fd is specified, <fs.WriteStream> will ignore the\npath argument and will use the specified file descriptor. This means that no\n'open' event will be emitted. fd should be blocking; non-blocking fds\nshould be passed to <net.Socket>.
Test whether or not the given path exists by checking with the file system.\nThen call the callback argument with either true or false:
import { exists } from 'node:fs';\n\nexists('/etc/passwd', (e) => {\n console.log(e ? 'it exists' : 'no passwd!');\n});\n
The parameters for this callback are not consistent with other Node.js\ncallbacks. Normally, the first parameter to a Node.js callback is an err\nparameter, optionally followed by other parameters. The fs.exists() callback\nhas only one boolean parameter. This is one reason fs.access() is recommended\ninstead of fs.exists().
err
fs.exists()
Using fs.exists() to check for the existence of a file before calling\nfs.open(), fs.readFile(), or fs.writeFile() is not recommended. Doing\nso introduces a race condition, since other processes may change the file's\nstate between the two calls. Instead, user code should open/read/write the\nfile directly and handle the error raised if the file does not exist.
import { exists, open, close } from 'node:fs';\n\nexists('myfile', (e) => {\n if (e) {\n console.error('myfile already exists');\n } else {\n open('myfile', 'wx', (err, fd) => {\n if (err) throw err;\n\n try {\n writeMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n });\n }\n});\n
import { open, close } from 'node:fs';\nopen('myfile', 'wx', (err, fd) => {\n if (err) {\n if (err.code === 'EEXIST') {\n console.error('myfile already exists');\n return;\n }\n\n throw err;\n }\n\n try {\n writeMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n});\n
import { open, close, exists } from 'node:fs';\n\nexists('myfile', (e) => {\n if (e) {\n open('myfile', 'r', (err, fd) => {\n if (err) throw err;\n\n try {\n readMyData(fd);\n } finally {\n close(fd, (err) => {\n if (err) throw err;\n });\n }\n });\n } else {\n console.error('myfile does not exist');\n }\n});\n
The \"not recommended\" examples above check for existence and then use the\nfile; the \"recommended\" examples are better because they use the file directly\nand handle the error, if any.
In general, check for the existence of a file only if the file won't be\nused directly, for example when its existence is a signal from another\nprocess.
Sets the permissions on the file. No arguments other than a possible exception\nare given to the completion callback.
See the POSIX fchmod(2) documentation for more detail.
fchmod(2)
Sets the owner of the file. No arguments other than a possible exception are\ngiven to the completion callback.
See the POSIX fchown(2) documentation for more detail.
fchown(2)
Forces all currently queued I/O operations associated with the file to the\noperating system's synchronized I/O completion state. Refer to the POSIX\nfdatasync(2) documentation for details. No arguments other than a possible\nexception are given to the completion callback.
Invokes the callback with the <fs.Stats> for the file descriptor.
See the POSIX fstat(2) documentation for more detail.
fstat(2)
Request that all data for the open file descriptor is flushed to the storage\ndevice. The specific implementation is operating system and device specific.\nRefer to the POSIX fsync(2) documentation for more detail. No arguments other\nthan a possible exception are given to the completion callback.
Truncates the file descriptor. No arguments other than a possible exception are\ngiven to the completion callback.
See the POSIX ftruncate(2) documentation for more detail.
ftruncate(2)
If the file referred to by the file descriptor was larger than len bytes, only\nthe first len bytes will be retained in the file.
For example, the following program retains only the first four bytes of the\nfile:
import { open, close, ftruncate } from 'node:fs';\n\nfunction closeFd(fd) {\n close(fd, (err) => {\n if (err) throw err;\n });\n}\n\nopen('temp.txt', 'r+', (err, fd) => {\n if (err) throw err;\n\n try {\n ftruncate(fd, 4, (err) => {\n closeFd(fd);\n if (err) throw err;\n });\n } catch (err) {\n closeFd(fd);\n if (err) throw err;\n }\n});\n
Change the file system timestamps of the object referenced by the supplied file\ndescriptor. See fs.utimes().
fs.utimes()
Changes the permissions on a symbolic link. No arguments other than a possible\nexception are given to the completion callback.
See the POSIX lchmod(2) documentation for more detail.
lchmod(2)
Set the owner of the symbolic link. No arguments other than a possible\nexception are given to the completion callback.
See the POSIX lchown(2) documentation for more detail.
lchown(2)
Changes the access and modification times of a file in the same way as\nfs.utimes(), with the difference that if the path refers to a symbolic\nlink, then the link is not dereferenced: instead, the timestamps of the\nsymbolic link itself are changed.
No arguments other than a possible exception are given to the completion\ncallback.
Creates a new link from the existingPath to the newPath. See the POSIX\nlink(2) documentation for more detail. No arguments other than a possible\nexception are given to the completion callback.
Retrieves the <fs.Stats> for the symbolic link referred to by the path.\nThe callback gets two arguments (err, stats) where stats is a <fs.Stats>\nobject. lstat() is identical to stat(), except that if path is a symbolic\nlink, then the link itself is stat-ed, not the file that it refers to.
(err, stats)
stats
lstat()
stat()
See the POSIX lstat(2) documentation for more details.
The callback is given a possible exception and, if recursive is true, the\nfirst directory path created, (err[, path]).\npath can still be undefined when recursive is true, if no directory was\ncreated.
(err[, path])
The optional options argument can be an integer specifying mode (permission\nand sticky bits), or an object with a mode property and a recursive\nproperty indicating whether parent directories should be created. Calling\nfs.mkdir() when path is a directory that exists results in an error only\nwhen recursive is false.
fs.mkdir()
import { mkdir } from 'node:fs';\n\n// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.\nmkdir('/tmp/a/apple', { recursive: true }, (err) => {\n if (err) throw err;\n});\n
On Windows, using fs.mkdir() on the root directory even with recursion will\nresult in an error:
import { mkdir } from 'node:fs';\n\nmkdir('/', { recursive: true }, (err) => {\n // => [Error: EPERM: operation not permitted, mkdir 'C:\\']\n});\n
See the POSIX mkdir(2) documentation for more details.
mkdir(2)
Creates a unique temporary directory.
Generates six random characters to be appended behind a required\nprefix to create a unique temporary directory. Due to platform\ninconsistencies, avoid trailing X characters in prefix. Some platforms,\nnotably the BSDs, can return more than six random characters, and replace\ntrailing X characters in prefix with random characters.
The created directory path is passed as a string to the callback's second\nparameter.
import { mkdtemp } from 'node:fs';\n\nmkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {\n if (err) throw err;\n console.log(directory);\n // Prints: /tmp/foo-itXde2 or C:\\Users\\...\\AppData\\Local\\Temp\\foo-itXde2\n});\n
The fs.mkdtemp() method will append the six randomly selected characters\ndirectly to the prefix string. For instance, given a directory /tmp, if the\nintention is to create a temporary directory within /tmp, the prefix\nmust end with a trailing platform-specific path separator\n(require('node:path').sep).
fs.mkdtemp()
import { tmpdir } from 'node:os';\nimport { mkdtemp } from 'node:fs';\n\n// The parent directory for the new temporary directory\nconst tmpDir = tmpdir();\n\n// This method is *INCORRECT*:\nmkdtemp(tmpDir, (err, directory) => {\n if (err) throw err;\n console.log(directory);\n // Will print something similar to `/tmpabc123`.\n // A new temporary directory is created at the file system root\n // rather than *within* the /tmp directory.\n});\n\n// This method is *CORRECT*:\nimport { sep } from 'node:path';\nmkdtemp(`${tmpDir}${sep}`, (err, directory) => {\n if (err) throw err;\n console.log(directory);\n // Will print something similar to `/tmp/abc123`.\n // A new temporary directory is created within\n // the /tmp directory.\n});\n
Asynchronous file open. See the POSIX open(2) documentation for more details.
mode sets the file mode (permission and sticky bits), but only if the file was\ncreated. On Windows, only the write permission can be manipulated; see\nfs.chmod().
The callback gets two arguments (err, fd).
(err, fd)
Functions based on fs.open() exhibit this behavior as well:\nfs.writeFile(), fs.readFile(), etc.
Asynchronously open a directory. See the POSIX opendir(3) documentation for\nmore details.
Read data from the file specified by fd.
The callback is given the three arguments, (err, bytesRead, buffer).
(err, bytesRead, buffer)
If this method is invoked as its util.promisify()ed version, it returns\na promise for an Object with bytesRead and buffer properties.
util.promisify()
Object
bytesRead
Similar to the fs.read() function, this version takes an optional\noptions object. If no options object is specified, it will default with the\nabove values.
fs.read()
Reads the contents of a directory. The callback gets two arguments (err, files)\nwhere files is an array of the names of the files in the directory excluding\n'.' and '..'.
(err, files)
files
'.'
'..'
See the POSIX readdir(3) documentation for more details.
readdir(3)
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames passed to the callback. If the encoding is set to 'buffer',\nthe filenames returned will be passed as <Buffer> objects.
If options.withFileTypes is set to true, the files array will contain\n<fs.Dirent> objects.
import { readFile } from 'node:fs';\n\nreadFile('/etc/passwd', (err, data) => {\n if (err) throw err;\n console.log(data);\n});\n
The callback is passed two arguments (err, data), where data is the\ncontents of the file.
(err, data)
If no encoding is specified, then the raw buffer is returned.
import { readFile } from 'node:fs';\n\nreadFile('/etc/passwd', 'utf8', callback);\n
When the path is a directory, the behavior of fs.readFile() and\nfs.readFileSync() is platform-specific. On macOS, Linux, and Windows, an\nerror will be returned. On FreeBSD, a representation of the directory's contents\nwill be returned.
fs.readFileSync()
import { readFile } from 'node:fs';\n\n// macOS, Linux, and Windows\nreadFile('<directory>', (err, data) => {\n // => [Error: EISDIR: illegal operation on a directory, read <directory>]\n});\n\n// FreeBSD\nreadFile('<directory>', (err, data) => {\n // => null, <data>\n});\n
It is possible to abort an ongoing request using an AbortSignal. If a\nrequest is aborted the callback is called with an AbortError:
AbortSignal
import { readFile } from 'node:fs';\n\nconst controller = new AbortController();\nconst signal = controller.signal;\nreadFile(fileInfo[0].name, { signal }, (err, buf) => {\n // ...\n});\n// When you want to abort the request\ncontroller.abort();\n
The fs.readFile() function buffers the entire file. To minimize memory costs,\nwhen possible prefer streaming via fs.createReadStream().
'Hello World
'World'
'Hello World'
The fs.readFile() method asynchronously reads the contents of a file into\nmemory one chunk at a time, allowing the event loop to turn between each chunk.\nThis allows the read operation to have less impact on other activity that may\nbe using the underlying libuv thread pool but means that it will take longer\nto read a complete file into memory.
The additional read overhead can vary broadly on different systems and depends\non the type of file being read. If the file type is not a regular file (a pipe\nfor instance) and Node.js is unable to determine an actual file size, each read\noperation will load on 64 KiB of data. For regular files, each read will process\n512 KiB of data.
For applications that require as-fast-as-possible reading of file contents, it\nis better to use fs.read() directly and for application code to manage\nreading the full contents of the file itself.
The Node.js GitHub issue #25741 provides more information and a detailed\nanalysis on the performance of fs.readFile() for multiple file sizes in\ndifferent Node.js versions.
Reads the contents of the symbolic link referred to by path. The callback gets\ntwo arguments (err, linkString).
(err, linkString)
See the POSIX readlink(2) documentation for more details.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path passed to the callback. If the encoding is set to 'buffer',\nthe link path returned will be passed as a <Buffer> object.
Read from a file specified by fd and write to an array of ArrayBufferViews\nusing readv().
ArrayBufferView
readv()
position is the offset from the beginning of the file from where data\nshould be read. If typeof position !== 'number', the data will be read\nfrom the current position.
position
typeof position !== 'number'
The callback will be given three arguments: err, bytesRead, and\nbuffers. bytesRead is how many bytes were read from the file.
If this method is invoked as its util.promisify()ed version, it returns\na promise for an Object with bytesRead and buffers properties.
Asynchronously computes the canonical pathname by resolving ., .., and\nsymbolic links.
.
..
A canonical pathname is not necessarily unique. Hard links and bind mounts can\nexpose a file system entity through many pathnames.
This function behaves like realpath(3), with some exceptions:
realpath(3)
No case conversion is performed on case-insensitive file systems.
The maximum number of symbolic links is platform-independent and generally\n(much) higher than what the native realpath(3) implementation supports.
The callback gets two arguments (err, resolvedPath). May use process.cwd\nto resolve relative paths.
(err, resolvedPath)
process.cwd
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path passed to the callback. If the encoding is set to 'buffer',\nthe path returned will be passed as a <Buffer> object.
If path resolves to a socket or a pipe, the function will return a system\ndependent name for that object.
Asynchronous realpath(3).
The callback gets two arguments (err, resolvedPath).
Asynchronously rename file at oldPath to the pathname provided\nas newPath. In the case that newPath already exists, it will\nbe overwritten. If there is a directory at newPath, an error will\nbe raised instead. No arguments other than a possible exception are\ngiven to the completion callback.
See also: rename(2).
rename(2)
import { rename } from 'node:fs';\n\nrename('oldFile.txt', 'newFile.txt', (err) => {\n if (err) throw err;\n console.log('Rename complete!');\n});\n
Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.
rmdir(2)
Using fs.rmdir() on a file (not a directory) results in an ENOENT error on\nWindows and an ENOTDIR error on POSIX.
fs.rmdir()
To get a behavior similar to the rm -rf Unix command, use fs.rm()\nwith options { recursive: true, force: true }.
fs.rm()
Asynchronously removes files and directories (modeled on the standard POSIX rm\nutility). No arguments other than a possible exception are given to the\ncompletion callback.
Asynchronous stat(2). The callback gets two arguments (err, stats) where\nstats is an <fs.Stats> object.
stat(2)
In case of an error, the err.code will be one of Common System Errors.
err.code
Using fs.stat() to check for the existence of a file before calling\nfs.open(), fs.readFile(), or fs.writeFile() is not recommended.\nInstead, user code should open/read/write the file directly and handle the\nerror raised if the file is not available.
fs.stat()
To check if a file exists without manipulating it afterwards, fs.access()\nis recommended.
For example, given the following directory structure:
- txtDir\n-- file.txt\n- app.js\n
The next program will check for the stats of the given paths:
import { stat } from 'node:fs';\n\nconst pathsToCheck = ['./txtDir', './txtDir/file.txt'];\n\nfor (let i = 0; i < pathsToCheck.length; i++) {\n stat(pathsToCheck[i], (err, stats) => {\n console.log(stats.isDirectory());\n console.log(stats);\n });\n}\n
The resulting output will resemble:
true\nStats {\n dev: 16777220,\n mode: 16877,\n nlink: 3,\n uid: 501,\n gid: 20,\n rdev: 0,\n blksize: 4096,\n ino: 14214262,\n size: 96,\n blocks: 0,\n atimeMs: 1561174653071.963,\n mtimeMs: 1561174614583.3518,\n ctimeMs: 1561174626623.5366,\n birthtimeMs: 1561174126937.2893,\n atime: 2019-06-22T03:37:33.072Z,\n mtime: 2019-06-22T03:36:54.583Z,\n ctime: 2019-06-22T03:37:06.624Z,\n birthtime: 2019-06-22T03:28:46.937Z\n}\nfalse\nStats {\n dev: 16777220,\n mode: 33188,\n nlink: 1,\n uid: 501,\n gid: 20,\n rdev: 0,\n blksize: 4096,\n ino: 14214074,\n size: 8,\n blocks: 8,\n atimeMs: 1561174616618.8555,\n mtimeMs: 1561174614584,\n ctimeMs: 1561174614583.8145,\n birthtimeMs: 1561174007710.7478,\n atime: 2019-06-22T03:36:56.619Z,\n mtime: 2019-06-22T03:36:54.584Z,\n ctime: 2019-06-22T03:36:54.584Z,\n birthtime: 2019-06-22T03:26:47.711Z\n}\n
Creates the link called path pointing to target. No arguments other than a\npossible exception are given to the completion callback.
See the POSIX symlink(2) documentation for more details.
symlink(2)
The type argument is only available on Windows and ignored on other platforms.\nIt can be set to 'dir', 'file', or 'junction'. If the type argument is\nnot a string, Node.js will autodetect target type and use 'file' or 'dir'.\nIf the target does not exist, 'file' will be used. Windows junction points\nrequire the destination path to be absolute. When using 'junction', the\ntarget argument will automatically be normalized to absolute path.
Relative targets are relative to the link's parent directory.
import { symlink } from 'node:fs';\n\nsymlink('./mew', './mewtwo', callback);\n
The above example creates a symbolic link mewtwo which points to mew in the\nsame directory:
mewtwo
mew
$ tree .\n.\n├── mew\n└── mewtwo -> ./mew\n
Truncates the file. No arguments other than a possible exception are\ngiven to the completion callback. A file descriptor can also be passed as the\nfirst argument. In this case, fs.ftruncate() is called.
fs.ftruncate()
import { truncate } from 'node:fs';\n// Assuming that 'path/file.txt' is a regular file.\ntruncate('path/file.txt', (err) => {\n if (err) throw err;\n console.log('path/file.txt was truncated');\n});\n
const { truncate } = require('node:fs');\n// Assuming that 'path/file.txt' is a regular file.\ntruncate('path/file.txt', (err) => {\n if (err) throw err;\n console.log('path/file.txt was truncated');\n});\n
Passing a file descriptor is deprecated and may result in an error being thrown\nin the future.
See the POSIX truncate(2) documentation for more details.
truncate(2)
Asynchronously removes a file or symbolic link. No arguments other than a\npossible exception are given to the completion callback.
import { unlink } from 'node:fs';\n// Assuming that 'path/file.txt' is a regular file.\nunlink('path/file.txt', (err) => {\n if (err) throw err;\n console.log('path/file.txt was deleted');\n});\n
fs.unlink() will not work on a directory, empty or otherwise. To remove a\ndirectory, use fs.rmdir().
fs.unlink()
See the POSIX unlink(2) documentation for more details.
Stop watching for changes on filename. If listener is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed,\neffectively stopping watching of filename.
listener
Calling fs.unwatchFile() with a filename that is not being watched is a\nno-op, not an error.
fs.unwatchFile()
Using fs.watch() is more efficient than fs.watchFile() and\nfs.unwatchFile(). fs.watch() should be used instead of fs.watchFile()\nand fs.unwatchFile() when possible.
fs.watchFile()
Watch for changes on filename, where filename is either a file or a\ndirectory.
The second argument is optional. If options is provided as a string, it\nspecifies the encoding. Otherwise options should be passed as an object.
The listener callback gets two arguments (eventType, filename). eventType\nis either 'rename' or 'change', and filename is the name of the file\nwhich triggered the event.
(eventType, filename)
eventType
'change'
The listener callback is attached to the 'change' event fired by\n<fs.FSWatcher>, but it is not the same thing as the 'change' value of\neventType.
If a signal is passed, aborting the corresponding AbortController will close\nthe returned <fs.FSWatcher>.
signal
The fs.watch API is not 100% consistent across platforms, and is\nunavailable in some situations.
fs.watch
The recursive option is only supported on macOS and Windows.\nAn ERR_FEATURE_UNAVAILABLE_ON_PLATFORM exception will be thrown\nwhen the option is used on a platform that does not support it.
ERR_FEATURE_UNAVAILABLE_ON_PLATFORM
On Windows, no events will be emitted if the watched directory is moved or\nrenamed. An EPERM error is reported when the watched directory is deleted.
EPERM
This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.
inotify(7)
kqueue(2)
FSEvents
event ports
ReadDirectoryChangesW
AHAFS
If the underlying functionality is not available for some reason, then\nfs.watch() will not be able to function and may throw an exception.\nFor example, watching files or directories can be unreliable, and in some\ncases impossible, on network file systems (NFS, SMB, etc) or host file systems\nwhen using virtualization software such as Vagrant or Docker.
It is still possible to use fs.watchFile(), which uses stat polling, but\nthis method is slower and less reliable.
On Linux and macOS systems, fs.watch() resolves the path to an inode and\nwatches the inode. If the watched path is deleted and recreated, it is assigned\na new inode. The watch will emit an event for the delete but will continue\nwatching the original inode. Events for the new inode will not be emitted.\nThis is expected behavior.
AIX files retain the same inode for the lifetime of a file. Saving and closing a\nwatched file on AIX will result in two notifications (one for adding new\ncontent, and one for truncation).
Providing filename argument in the callback is only supported on Linux,\nmacOS, Windows, and AIX. Even on supported platforms, filename is not always\nguaranteed to be provided. Therefore, don't assume that filename argument is\nalways provided in the callback, and have some fallback logic if it is null.
import { watch } from 'node:fs';\nwatch('somedir', (eventType, filename) => {\n console.log(`event type is: ${eventType}`);\n if (filename) {\n console.log(`filename provided: ${filename}`);\n } else {\n console.log('filename not provided');\n }\n});\n
Watch for changes on filename. The callback listener will be called each\ntime the file is accessed.
The options argument may be omitted. If provided, it should be an object. The\noptions object may contain a boolean named persistent that indicates\nwhether the process should continue to run as long as files are being watched.\nThe options object may specify an interval property indicating how often the\ntarget should be polled in milliseconds.
persistent
interval
The listener gets two arguments the current stat object and the previous\nstat object:
import { watchFile } from 'node:fs';\n\nwatchFile('message.text', (curr, prev) => {\n console.log(`the current mtime is: ${curr.mtime}`);\n console.log(`the previous mtime was: ${prev.mtime}`);\n});\n
These stat objects are instances of fs.Stat. If the bigint option is true,\nthe numeric values in these objects are specified as BigInts.
fs.Stat
bigint
BigInt
To be notified when the file was modified, not just accessed, it is necessary\nto compare curr.mtimeMs and prev.mtimeMs.
curr.mtimeMs
prev.mtimeMs
When an fs.watchFile operation results in an ENOENT error, it\nwill invoke the listener once, with all the fields zeroed (or, for dates, the\nUnix Epoch). If the file is created later on, the listener will be called\nagain, with the latest stat objects. This is a change in functionality since\nv0.10.
fs.watchFile
Using fs.watch() is more efficient than fs.watchFile and\nfs.unwatchFile. fs.watch should be used instead of fs.watchFile and\nfs.unwatchFile when possible.
fs.unwatchFile
When a file being watched by fs.watchFile() disappears and reappears,\nthen the contents of previous in the second callback event (the file's\nreappearance) will be the same as the contents of previous in the first\ncallback event (its disappearance).
previous
This happens when:
Write buffer to the file specified by fd.
offset determines the part of the buffer to be written, and length is\nan integer specifying the number of bytes to write.
offset
length
position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position. See pwrite(2).
pwrite(2)
The callback will be given three arguments (err, bytesWritten, buffer) where\nbytesWritten specifies how many bytes were written from buffer.
(err, bytesWritten, buffer)
If this method is invoked as its util.promisify()ed version, it returns\na promise for an Object with bytesWritten and buffer properties.
It is unsafe to use fs.write() multiple times on the same file without waiting\nfor the callback. For this scenario, fs.createWriteStream() is\nrecommended.
fs.write()
Similar to the above fs.write function, this version takes an\noptional options object. If no options object is specified, it will\ndefault with the above values.
fs.write
Write string to the file specified by fd. If string is not a string, or an\nobject with an own toString function property, then an exception is thrown.
toString
position refers to the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number' the data will be written at\nthe current position. See pwrite(2).
encoding is the expected string encoding.
The callback will receive the arguments (err, written, string) where written\nspecifies how many bytes the passed string required to be written. Bytes\nwritten is not necessarily the same as string characters written. See\nBuffer.byteLength.
(err, written, string)
written
Buffer.byteLength
On Windows, if the file descriptor is connected to the console (e.g. fd == 1\nor stdout) a string containing non-ASCII characters will not be rendered\nproperly by default, regardless of the encoding used.\nIt is possible to configure the console to render UTF-8 properly by changing the\nactive codepage with the chcp 65001 command. See the chcp docs for more\ndetails.
fd == 1
stdout
chcp 65001
When file is a filename, asynchronously writes data to the file, replacing the\nfile if it already exists. data can be a string or a buffer.
file
When file is a file descriptor, the behavior is similar to calling\nfs.write() directly (which is recommended). See the notes below on using\na file descriptor.
If data is a plain object, it must have an own (not inherited) toString\nfunction property.
import { writeFile } from 'node:fs';\nimport { Buffer } from 'node:buffer';\n\nconst data = new Uint8Array(Buffer.from('Hello Node.js'));\nwriteFile('message.txt', data, (err) => {\n if (err) throw err;\n console.log('The file has been saved!');\n});\n
import { writeFile } from 'node:fs';\n\nwriteFile('message.txt', 'Hello Node.js', 'utf8', callback);\n
It is unsafe to use fs.writeFile() multiple times on the same file without\nwaiting for the callback. For this scenario, fs.createWriteStream() is\nrecommended.
Similarly to fs.readFile - fs.writeFile is a convenience method that\nperforms multiple write calls internally to write the buffer passed to it.\nFor performance sensitive code consider using fs.createWriteStream().
It is possible to use an <AbortSignal> to cancel an fs.writeFile().\nCancelation is \"best effort\", and some amount of data is likely still\nto be written.
import { writeFile } from 'node:fs';\nimport { Buffer } from 'node:buffer';\n\nconst controller = new AbortController();\nconst { signal } = controller;\nconst data = new Uint8Array(Buffer.from('Hello Node.js'));\nwriteFile('message.txt', data, { signal }, (err) => {\n // When a request is aborted - the callback is called with an AbortError\n});\n// When the request should be aborted\ncontroller.abort();\n
When file is a file descriptor, the behavior is almost identical to directly\ncalling fs.write() like:
import { write } from 'node:fs';\nimport { Buffer } from 'node:buffer';\n\nwrite(fd, Buffer.from(data, options.encoding), callback);\n
The difference from directly calling fs.write() is that under some unusual\nconditions, fs.write() might write only part of the buffer and need to be\nretried to write the remaining data, whereas fs.writeFile() retries until\nthe data is entirely written (or an error occurs).
The implications of this are a common source of confusion. In\nthe file descriptor case, the file is not replaced! The data is not necessarily\nwritten to the beginning of the file, and the file's original data may remain\nbefore and/or after the newly written data.
For example, if fs.writeFile() is called twice in a row, first to write the\nstring 'Hello', then to write the string ', World', the file would contain\n'Hello, World', and might contain some of the file's original data (depending\non the size of the original file, and the position of the file descriptor). If\na file name had been used instead of a descriptor, the file would be guaranteed\nto contain only ', World'.
'Hello'
', World'
'Hello, World'
Write an array of ArrayBufferViews to the file specified by fd using\nwritev().
position is the offset from the beginning of the file where this data\nshould be written. If typeof position !== 'number', the data will be written\nat the current position.
The callback will be given three arguments: err, bytesWritten, and\nbuffers. bytesWritten is how many bytes were written from buffers.
If this method is util.promisify()ed, it returns a promise for an\nObject with bytesWritten and buffers properties.
It is unsafe to use fs.writev() multiple times on the same file without\nwaiting for the callback. For this scenario, use fs.createWriteStream().
fs.writev()
The synchronous APIs perform all operations synchronously, blocking the\nevent loop until the operation completes or fails.
Synchronously tests a user's permissions for the file or directory specified\nby path. The mode argument is an optional integer that specifies the\naccessibility checks to be performed. mode should be either the value\nfs.constants.F_OK or a mask consisting of the bitwise OR of any of\nfs.constants.R_OK, fs.constants.W_OK, and fs.constants.X_OK (e.g.\nfs.constants.W_OK | fs.constants.R_OK). Check File access constants for\npossible values of mode.
If any of the accessibility checks fail, an Error will be thrown. Otherwise,\nthe method will return undefined.
import { accessSync, constants } from 'node:fs';\n\ntry {\n accessSync('etc/passwd', constants.R_OK | constants.W_OK);\n console.log('can read/write');\n} catch (err) {\n console.error('no access!');\n}\n
Synchronously append data to a file, creating the file if it does not yet\nexist. data can be a string or a <Buffer>.
import { appendFileSync } from 'node:fs';\n\ntry {\n appendFileSync('message.txt', 'data to append');\n console.log('The \"data to append\" was appended to file!');\n} catch (err) {\n /* Handle the error */\n}\n
import { appendFileSync } from 'node:fs';\n\nappendFileSync('message.txt', 'data to append', 'utf8');\n
import { openSync, closeSync, appendFileSync } from 'node:fs';\n\nlet fd;\n\ntry {\n fd = openSync('message.txt', 'a');\n appendFileSync(fd, 'data to append', 'utf8');\n} catch (err) {\n /* Handle the error */\n} finally {\n if (fd !== undefined)\n closeSync(fd);\n}\n
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.chmod().
Synchronously changes owner and group of a file. Returns undefined.\nThis is the synchronous version of fs.chown().
fs.chown()
Closes the file descriptor. Returns undefined.
Calling fs.closeSync() on any file descriptor (fd) that is currently in use\nthrough any other fs operation may lead to undefined behavior.
fs.closeSync()
Synchronously copies src to dest. By default, dest is overwritten if it\nalready exists. Returns undefined. Node.js makes no guarantees about the\natomicity of the copy operation. If an error occurs after the destination file\nhas been opened for writing, Node.js will attempt to remove the destination.
import { copyFileSync, constants } from 'node:fs';\n\n// destination.txt will be created or overwritten by default.\ncopyFileSync('source.txt', 'destination.txt');\nconsole.log('source.txt was copied to destination.txt');\n\n// By using COPYFILE_EXCL, the operation will fail if destination.txt exists.\ncopyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);\n
Synchronously copies the entire directory structure from src to dest,\nincluding subdirectories and files.
Returns true if the path exists, false otherwise.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.exists().
fs.exists() is deprecated, but fs.existsSync() is not. The callback\nparameter to fs.exists() accepts parameters that are inconsistent with other\nNode.js callbacks. fs.existsSync() does not use a callback.
fs.existsSync()
import { existsSync } from 'node:fs';\n\nif (existsSync('/etc/passwd'))\n console.log('The path exists.');\n
Sets the permissions on the file. Returns undefined.
Sets the owner of the file. Returns undefined.
Forces all currently queued I/O operations associated with the file to the\noperating system's synchronized I/O completion state. Refer to the POSIX\nfdatasync(2) documentation for details. Returns undefined.
Retrieves the <fs.Stats> for the file descriptor.
Request that all data for the open file descriptor is flushed to the storage\ndevice. The specific implementation is operating system and device specific.\nRefer to the POSIX fsync(2) documentation for more detail. Returns undefined.
Truncates the file descriptor. Returns undefined.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.ftruncate().
Synchronous version of fs.futimes(). Returns undefined.
fs.futimes()
Changes the permissions on a symbolic link. Returns undefined.
Set the owner for the path. Returns undefined.
See the POSIX lchown(2) documentation for more details.
Change the file system timestamps of the symbolic link referenced by path.\nReturns undefined, or throws an exception when parameters are incorrect or\nthe operation fails. This is the synchronous version of fs.lutimes().
fs.lutimes()
Creates a new link from the existingPath to the newPath. See the POSIX\nlink(2) documentation for more detail. Returns undefined.
Retrieves the <fs.Stats> for the symbolic link referred to by path.
Synchronously creates a directory. Returns undefined, or if recursive is\ntrue, the first directory path created.\nThis is the synchronous version of fs.mkdir().
Returns the created directory path.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.mkdtemp().
Synchronously open a directory. See opendir(3).
Returns an integer representing the file descriptor.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.open().
Reads the contents of the directory.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe filenames returned. If the encoding is set to 'buffer',\nthe filenames returned will be passed as <Buffer> objects.
If options.withFileTypes is set to true, the result will contain\n<fs.Dirent> objects.
Returns the contents of the path.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readFile().
If the encoding option is specified then this function returns a\nstring. Otherwise it returns a buffer.
Similar to fs.readFile(), when the path is a directory, the behavior of\nfs.readFileSync() is platform-specific.
import { readFileSync } from 'node:fs';\n\n// macOS, Linux, and Windows\nreadFileSync('<directory>');\n// => [Error: EISDIR: illegal operation on a directory, read <directory>]\n\n// FreeBSD\nreadFileSync('<directory>'); // => <data>\n
Returns the symbolic link's string value.
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe link path returned. If the encoding is set to 'buffer',\nthe link path returned will be passed as a <Buffer> object.
Returns the number of bytesRead.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.read().
Similar to the above fs.readSync function, this version takes an optional options object.\nIf no options object is specified, it will default with the above values.
fs.readSync
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.readv().
fs.readv()
Returns the resolved pathname.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.realpath().
fs.realpath()
Synchronous realpath(3).
The optional options argument can be a string specifying an encoding, or an\nobject with an encoding property specifying the character encoding to use for\nthe path returned. If the encoding is set to 'buffer',\nthe path returned will be passed as a <Buffer> object.
Renames the file from oldPath to newPath. Returns undefined.
See the POSIX rename(2) documentation for more details.
Synchronous rmdir(2). Returns undefined.
Using fs.rmdirSync() on a file (not a directory) results in an ENOENT error\non Windows and an ENOTDIR error on POSIX.
fs.rmdirSync()
To get a behavior similar to the rm -rf Unix command, use fs.rmSync()\nwith options { recursive: true, force: true }.
fs.rmSync()
Synchronously removes files and directories (modeled on the standard POSIX rm\nutility). Returns undefined.
Retrieves the <fs.Stats> for the path.
Returns undefined.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.symlink().
fs.symlink()
Truncates the file. Returns undefined. A file descriptor can also be\npassed as the first argument. In this case, fs.ftruncateSync() is called.
fs.ftruncateSync()
Synchronous unlink(2). Returns undefined.
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.utimes().
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writeFile().
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, buffer...).
fs.write(fd, buffer...)
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.write(fd, string...).
fs.write(fd, string...)
For detailed information, see the documentation of the asynchronous version of\nthis API: fs.writev().
The common objects are shared by all of the file system API variants\n(promise, callback, and synchronous).
A class representing a directory stream.
Created by fs.opendir(), fs.opendirSync(), or\nfsPromises.opendir().
fs.opendir()
fs.opendirSync()
fsPromises.opendir()
Asynchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.
A promise is returned that will be resolved after the resource has been\nclosed.
The callback will be called after the resource handle has been closed.
Synchronously close the directory's underlying resource handle.\nSubsequent reads will result in errors.
Asynchronously read the next directory entry via readdir(3) as an\n<fs.Dirent>.
A promise is returned that will be resolved with an <fs.Dirent>, or null\nif there are no more directory entries to read.
Directory entries returned by this function are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory might not be\nincluded in the iteration results.
After the read is completed, the callback will be called with an\n<fs.Dirent>, or null if there are no more directory entries to read.
Synchronously read the next directory entry as an <fs.Dirent>. See the\nPOSIX readdir(3) documentation for more detail.
If there are no more directory entries to read, null will be returned.
Asynchronously iterates over the directory until all entries have\nbeen read. Refer to the POSIX readdir(3) documentation for more detail.
Entries returned by the async iterator are always an <fs.Dirent>.\nThe null case from dir.read() is handled internally.
dir.read()
See <fs.Dir> for an example.
Directory entries returned by this iterator are in no particular order as\nprovided by the operating system's underlying directory mechanisms.\nEntries added or removed while iterating over the directory might not be\nincluded in the iteration results.
The read-only path of this directory as was provided to fs.opendir(),\nfs.opendirSync(), or fsPromises.opendir().
A representation of a directory entry, which can be a file or a subdirectory\nwithin the directory, as returned by reading from an <fs.Dir>. The\ndirectory entry is a combination of the file name and file type pairs.
Additionally, when fs.readdir() or fs.readdirSync() is called with\nthe withFileTypes option set to true, the resulting array is filled with\n<fs.Dirent> objects, rather than strings or <Buffer>s.
fs.readdir()
fs.readdirSync()
withFileTypes
Returns true if the <fs.Dirent> object describes a block device.
Returns true if the <fs.Dirent> object describes a character device.
Returns true if the <fs.Dirent> object describes a file system\ndirectory.
Returns true if the <fs.Dirent> object describes a first-in-first-out\n(FIFO) pipe.
Returns true if the <fs.Dirent> object describes a regular file.
Returns true if the <fs.Dirent> object describes a socket.
Returns true if the <fs.Dirent> object describes a symbolic link.
The file name that this <fs.Dirent> object refers to. The type of this\nvalue is determined by the options.encoding passed to fs.readdir() or\nfs.readdirSync().
A successful call to fs.watch() method will return a new <fs.FSWatcher>\nobject.
All <fs.FSWatcher> objects emit a 'change' event whenever a specific watched\nfile is modified.
Emitted when something changes in a watched directory or file.\nSee more details in fs.watch().
The filename argument may not be provided depending on operating system\nsupport. If filename is provided, it will be provided as a <Buffer> if\nfs.watch() is called with its encoding option set to 'buffer', otherwise\nfilename will be a UTF-8 string.
import { watch } from 'node:fs';\n// Example when handled through fs.watch() listener\nwatch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {\n if (filename) {\n console.log(filename);\n // Prints: <Buffer ...>\n }\n});\n
Emitted when the watcher stops watching for changes. The closed\n<fs.FSWatcher> object is no longer usable in the event handler.
Emitted when an error occurs while watching the file. The errored\n<fs.FSWatcher> object is no longer usable in the event handler.
Stop watching for changes on the given <fs.FSWatcher>. Once stopped, the\n<fs.FSWatcher> object is no longer usable.
When called, requests that the Node.js event loop not exit so long as the\n<fs.FSWatcher> is active. Calling watcher.ref() multiple times will have\nno effect.
watcher.ref()
By default, all <fs.FSWatcher> objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.
watcher.unref()
When called, the active <fs.FSWatcher> object will not require the Node.js\nevent loop to remain active. If there is no other activity keeping the\nevent loop running, the process may exit before the <fs.FSWatcher> object's\ncallback is invoked. Calling watcher.unref() multiple times will have\nno effect.
A successful call to fs.watchFile() method will return a new <fs.StatWatcher>\nobject.
When called, requests that the Node.js event loop not exit so long as the\n<fs.StatWatcher> is active. Calling watcher.ref() multiple times will have\nno effect.
By default, all <fs.StatWatcher> objects are \"ref'ed\", making it normally\nunnecessary to call watcher.ref() unless watcher.unref() had been\ncalled previously.
When called, the active <fs.StatWatcher> object will not require the Node.js\nevent loop to remain active. If there is no other activity keeping the\nevent loop running, the process may exit before the <fs.StatWatcher> object's\ncallback is invoked. Calling watcher.unref() multiple times will have\nno effect.
Instances of <fs.ReadStream> are created and returned using the\nfs.createReadStream() function.
Emitted when the <fs.ReadStream>'s underlying file descriptor has been closed.
Emitted when the <fs.ReadStream>'s file descriptor has been opened.
Emitted when the <fs.ReadStream> is ready to be used.
Fires immediately after 'open'.
The number of bytes that have been read so far.
The path to the file the stream is reading from as specified in the first\nargument to fs.createReadStream(). If path is passed as a string, then\nreadStream.path will be a string. If path is passed as a <Buffer>, then\nreadStream.path will be a <Buffer>. If fd is specified, then\nreadStream.path will be undefined.
readStream.path
This property is true if the underlying file has not been opened yet,\ni.e. before the 'ready' event is emitted.
'ready'
A <fs.Stats> object provides information about a file.
Objects returned from fs.stat(), fs.lstat(), fs.fstat(), and\ntheir synchronous counterparts are of this type.\nIf bigint in the options passed to those methods is true, the numeric values\nwill be bigint instead of number, and the object will contain additional\nnanosecond-precision properties suffixed with Ns.
fs.lstat()
fs.fstat()
number
Ns
Stats {\n dev: 2114,\n ino: 48064969,\n mode: 33188,\n nlink: 1,\n uid: 85,\n gid: 100,\n rdev: 0,\n size: 527,\n blksize: 4096,\n blocks: 8,\n atimeMs: 1318289051000.1,\n mtimeMs: 1318289051000.1,\n ctimeMs: 1318289051000.1,\n birthtimeMs: 1318289051000.1,\n atime: Mon, 10 Oct 2011 23:24:11 GMT,\n mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n ctime: Mon, 10 Oct 2011 23:24:11 GMT,\n birthtime: Mon, 10 Oct 2011 23:24:11 GMT }\n
bigint version:
BigIntStats {\n dev: 2114n,\n ino: 48064969n,\n mode: 33188n,\n nlink: 1n,\n uid: 85n,\n gid: 100n,\n rdev: 0n,\n size: 527n,\n blksize: 4096n,\n blocks: 8n,\n atimeMs: 1318289051000n,\n mtimeMs: 1318289051000n,\n ctimeMs: 1318289051000n,\n birthtimeMs: 1318289051000n,\n atimeNs: 1318289051000000000n,\n mtimeNs: 1318289051000000000n,\n ctimeNs: 1318289051000000000n,\n birthtimeNs: 1318289051000000000n,\n atime: Mon, 10 Oct 2011 23:24:11 GMT,\n mtime: Mon, 10 Oct 2011 23:24:11 GMT,\n ctime: Mon, 10 Oct 2011 23:24:11 GMT,\n birthtime: Mon, 10 Oct 2011 23:24:11 GMT }\n
Returns true if the <fs.Stats> object describes a block device.
Returns true if the <fs.Stats> object describes a character device.
Returns true if the <fs.Stats> object describes a file system directory.
If the <fs.Stats> object was obtained from fs.lstat(), this method will\nalways return false. This is because fs.lstat() returns information\nabout a symbolic link itself and not the path it resolves to.
Returns true if the <fs.Stats> object describes a first-in-first-out (FIFO)\npipe.
Returns true if the <fs.Stats> object describes a regular file.
Returns true if the <fs.Stats> object describes a socket.
Returns true if the <fs.Stats> object describes a symbolic link.
This method is only valid when using fs.lstat().
The numeric identifier of the device containing the file.
The file system specific \"Inode\" number for the file.
A bit-field describing the file type and mode.
The number of hard-links that exist for the file.
The numeric user identifier of the user that owns the file (POSIX).
The numeric group identifier of the group that owns the file (POSIX).
A numeric device identifier if the file represents a device.
The size of the file in bytes.
If the underlying file system does not support getting the size of the file,\nthis will be 0.
The file system block size for i/o operations.
The number of blocks allocated for this file.
The timestamp indicating the last time this file was accessed expressed in\nmilliseconds since the POSIX Epoch.
The timestamp indicating the last time this file was modified expressed in\nmilliseconds since the POSIX Epoch.
The timestamp indicating the last time the file status was changed expressed\nin milliseconds since the POSIX Epoch.
The timestamp indicating the creation time of this file expressed in\nmilliseconds since the POSIX Epoch.
Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time this file was accessed expressed in\nnanoseconds since the POSIX Epoch.
bigint: true
Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time this file was modified expressed in\nnanoseconds since the POSIX Epoch.
Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the last time the file status was changed expressed\nin nanoseconds since the POSIX Epoch.
Only present when bigint: true is passed into the method that generates\nthe object.\nThe timestamp indicating the creation time of this file expressed in\nnanoseconds since the POSIX Epoch.
The timestamp indicating the last time this file was accessed.
The timestamp indicating the last time this file was modified.
The timestamp indicating the last time the file status was changed.
The timestamp indicating the creation time of this file.
The atimeMs, mtimeMs, ctimeMs, birthtimeMs properties are\nnumeric values that hold the corresponding times in milliseconds. Their\nprecision is platform specific. When bigint: true is passed into the\nmethod that generates the object, the properties will be bigints,\notherwise they will be numbers.
atimeMs
mtimeMs
ctimeMs
birthtimeMs
The atimeNs, mtimeNs, ctimeNs, birthtimeNs properties are\nbigints that hold the corresponding times in nanoseconds. They are\nonly present when bigint: true is passed into the method that generates\nthe object. Their precision is platform specific.
atimeNs
mtimeNs
ctimeNs
birthtimeNs
atime, mtime, ctime, and birthtime are\nDate object alternate representations of the various times. The\nDate and number values are not connected. Assigning a new number value, or\nmutating the Date value, will not be reflected in the corresponding alternate\nrepresentation.
ctime
birthtime
The times in the stat object have the following semantics:
mknod(2)
utimes(2)
read(2)
write(2)
1970-01-01T00:00Z
Prior to Node.js 0.12, the ctime held the birthtime on Windows systems. As\nof 0.12, ctime is not \"creation time\", and on Unix systems, it never was.
Instances of <fs.WriteStream> are created and returned using the\nfs.createWriteStream() function.
Emitted when the <fs.WriteStream>'s underlying file descriptor has been closed.
Emitted when the <fs.WriteStream>'s file is opened.
Emitted when the <fs.WriteStream> is ready to be used.
The number of bytes written so far. Does not include data that is still queued\nfor writing.
The path to the file the stream is writing to as specified in the first\nargument to fs.createWriteStream(). If path is passed as a string, then\nwriteStream.path will be a string. If path is passed as a <Buffer>, then\nwriteStream.path will be a <Buffer>.
writeStream.path
Closes writeStream. Optionally accepts a\ncallback that will be executed once the writeStream\nis closed.
writeStream
Returns an object containing commonly used constants for file system\noperations.
The following constants are exported by fs.constants and fsPromises.constants.
fsPromises.constants
Not every constant will be available on every operating system;\nthis is especially important for Windows, where many of the POSIX specific\ndefinitions are not available.\nFor portable applications it is recommended to check for their presence\nbefore use.
To use more than one constant, use the bitwise OR | operator.
|
Example:
import { open, constants } from 'node:fs';\n\nconst {\n O_RDWR,\n O_CREAT,\n O_EXCL\n} = constants;\n\nopen('/path/to/my/file', O_RDWR | O_CREAT | O_EXCL, (err, fd) => {\n // ...\n});\n
The following constants are meant for use as the mode parameter passed to\nfsPromises.access(), fs.access(), and fs.accessSync().
fs.accessSync()
F_OK
rwx
R_OK
W_OK
X_OK
The definitions are also available on Windows.
The following constants are meant for use with fs.copyFile().
fs.copyFile()
COPYFILE_EXCL
COPYFILE_FICLONE
COPYFILE_FICLONE_FORCE
The following constants are meant for use with fs.open().
O_RDONLY
O_WRONLY
O_RDWR
O_CREAT
O_EXCL
O_NOCTTY
O_TRUNC
O_APPEND
O_DIRECTORY
O_NOATIME
O_NOFOLLOW
O_SYNC
O_DSYNC
O_SYMLINK
O_DIRECT
O_NONBLOCK
UV_FS_O_FILEMAP
On Windows, only O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR,\nO_TRUNC, O_WRONLY, and UV_FS_O_FILEMAP are available.
The following constants are meant for use with the <fs.Stats> object's\nmode property for determining a file's type.
S_IFMT
S_IFREG
S_IFDIR
S_IFCHR
S_IFBLK
S_IFIFO
S_IFLNK
S_IFSOCK
On Windows, only S_IFCHR, S_IFDIR, S_IFLNK, S_IFMT, and S_IFREG,\nare available.
The following constants are meant for use with the <fs.Stats> object's\nmode property for determining the access permissions for a file.
S_IRWXU
S_IRUSR
S_IWUSR
S_IXUSR
S_IRWXG
S_IRGRP
S_IWGRP
S_IXGRP
S_IRWXO
S_IROTH
S_IWOTH
S_IXOTH
On Windows, only S_IRUSR and S_IWUSR are available.
Because they are executed asynchronously by the underlying thread pool,\nthere is no guaranteed ordering when using either the callback or\npromise-based methods.
For example, the following is prone to error because the fs.stat()\noperation might complete before the fs.rename() operation:
fs.rename()
fs.rename('/tmp/hello', '/tmp/world', (err) => {\n if (err) throw err;\n console.log('renamed complete');\n});\nfs.stat('/tmp/world', (err, stats) => {\n if (err) throw err;\n console.log(`stats: ${JSON.stringify(stats)}`);\n});\n
It is important to correctly order the operations by awaiting the results\nof one before invoking the other:
import { rename, stat } from 'node:fs/promises';\n\nconst from = '/tmp/hello';\nconst to = '/tmp/world';\n\ntry {\n await rename(from, to);\n const stats = await stat(to);\n console.log(`stats: ${JSON.stringify(stats)}`);\n} catch (error) {\n console.error('there was an error:', error.message);\n}\n
const { rename, stat } = require('node:fs/promises');\n\n(async function(from, to) {\n try {\n await rename(from, to);\n const stats = await stat(to);\n console.log(`stats: ${JSON.stringify(stats)}`);\n } catch (error) {\n console.error('there was an error:', error.message);\n }\n})('/tmp/hello', '/tmp/world');\n
Or, when using the callback APIs, move the fs.stat() call into the callback\nof the fs.rename() operation:
import { rename, stat } from 'node:fs';\n\nrename('/tmp/hello', '/tmp/world', (err) => {\n if (err) throw err;\n stat('/tmp/world', (err, stats) => {\n if (err) throw err;\n console.log(`stats: ${JSON.stringify(stats)}`);\n });\n});\n
const { rename, stat } = require('node:fs/promises');\n\nrename('/tmp/hello', '/tmp/world', (err) => {\n if (err) throw err;\n stat('/tmp/world', (err, stats) => {\n if (err) throw err;\n console.log(`stats: ${JSON.stringify(stats)}`);\n });\n});\n
Most fs operations accept file paths that may be specified in the form of\na string, a <Buffer>, or a <URL> object using the file: protocol.
file:
String paths are interpreted as UTF-8 character sequences identifying\nthe absolute or relative filename. Relative paths will be resolved relative\nto the current working directory as determined by calling process.cwd().
process.cwd()
Example using an absolute path on POSIX:
import { open } from 'node:fs/promises';\n\nlet fd;\ntry {\n fd = await open('/open/some/file.txt', 'r');\n // Do something with the file\n} finally {\n await fd.close();\n}\n
Example using a relative path on POSIX (relative to process.cwd()):
import { open } from 'node:fs/promises';\n\nlet fd;\ntry {\n fd = await open('file.txt', 'r');\n // Do something with the file\n} finally {\n await fd.close();\n}\n
For most node:fs module functions, the path or filename argument may be\npassed as a <URL> object using the file: protocol.
import { readFileSync } from 'node:fs';\n\nreadFileSync(new URL('file:///tmp/hello'));\n
file: URLs are always absolute paths.
On Windows, file: <URL>s with a host name convert to UNC paths, while file:\n<URL>s with drive letters convert to local absolute paths. file: <URL>s\nwith no host name and no drive letter will result in an error:
import { readFileSync } from 'node:fs';\n// On Windows :\n\n// - WHATWG file URLs with hostname convert to UNC path\n// file://hostname/p/a/t/h/file => \\\\hostname\\p\\a\\t\\h\\file\nreadFileSync(new URL('file://hostname/p/a/t/h/file'));\n\n// - WHATWG file URLs with drive letters convert to absolute path\n// file:///C:/tmp/hello => C:\\tmp\\hello\nreadFileSync(new URL('file:///C:/tmp/hello'));\n\n// - WHATWG file URLs without hostname must have a drive letters\nreadFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));\nreadFileSync(new URL('file:///c/p/a/t/h/file'));\n// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute\n
file: <URL>s with drive letters must use : as a separator just after\nthe drive letter. Using another separator will result in an error.
:
On all other platforms, file: <URL>s with a host name are unsupported and\nwill result in an error:
import { readFileSync } from 'node:fs';\n// On other platforms:\n\n// - WHATWG file URLs with hostname are unsupported\n// file://hostname/p/a/t/h/file => throw!\nreadFileSync(new URL('file://hostname/p/a/t/h/file'));\n// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute\n\n// - WHATWG file URLs convert to absolute path\n// file:///tmp/hello => /tmp/hello\nreadFileSync(new URL('file:///tmp/hello'));\n
A file: <URL> having encoded slash characters will result in an error on all\nplatforms:
import { readFileSync } from 'node:fs';\n\n// On Windows\nreadFileSync(new URL('file:///C:/p/a/t/h/%2F'));\nreadFileSync(new URL('file:///C:/p/a/t/h/%2f'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n\\ or / characters */\n\n// On POSIX\nreadFileSync(new URL('file:///p/a/t/h/%2F'));\nreadFileSync(new URL('file:///p/a/t/h/%2f'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n/ characters */\n
On Windows, file: <URL>s having encoded backslash will result in an error:
import { readFileSync } from 'node:fs';\n\n// On Windows\nreadFileSync(new URL('file:///C:/path/%5C'));\nreadFileSync(new URL('file:///C:/path/%5c'));\n/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded\n\\ or / characters */\n
Paths specified using a <Buffer> are useful primarily on certain POSIX\noperating systems that treat file paths as opaque byte sequences. On such\nsystems, it is possible for a single file path to contain sub-sequences that\nuse multiple character encodings. As with string paths, <Buffer> paths may\nbe relative or absolute:
import { open } from 'node:fs/promises';\nimport { Buffer } from 'node:buffer';\n\nlet fd;\ntry {\n fd = await open(Buffer.from('/open/some/file.txt'), 'r');\n // Do something with the file\n} finally {\n await fd.close();\n}\n
On Windows, Node.js follows the concept of per-drive working directory. This\nbehavior can be observed when using a drive path without a backslash. For\nexample fs.readdirSync('C:\\\\') can potentially return a different result than\nfs.readdirSync('C:'). For more information, see\nthis MSDN page.
fs.readdirSync('C:\\\\')
fs.readdirSync('C:')
On POSIX systems, for every process, the kernel maintains a table of currently\nopen files and resources. Each open file is assigned a simple numeric\nidentifier called a file descriptor. At the system-level, all file system\noperations use these file descriptors to identify and track each specific\nfile. Windows systems use a different but conceptually similar mechanism for\ntracking resources. To simplify things for users, Node.js abstracts away the\ndifferences between operating systems and assigns all open files a numeric file\ndescriptor.
The callback-based fs.open(), and synchronous fs.openSync() methods open a\nfile and allocate a new file descriptor. Once allocated, the file descriptor may\nbe 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 open\nat any given time so it is critical to close the descriptor when operations\nare completed. Failure to do so will result in a memory leak that will\neventually cause an application to crash.
import { open, close, fstat } from 'node:fs';\n\nfunction closeFd(fd) {\n close(fd, (err) => {\n if (err) throw err;\n });\n}\n\nopen('/open/some/file.txt', 'r', (err, fd) => {\n if (err) throw err;\n try {\n fstat(fd, (err, stat) => {\n if (err) {\n closeFd(fd);\n throw err;\n }\n\n // use stat\n\n closeFd(fd);\n });\n } catch (err) {\n closeFd(fd);\n throw err;\n }\n});\n
The promise-based APIs use a <FileHandle> object in place of the numeric\nfile descriptor. These objects are better managed by the system to ensure\nthat resources are not leaked. However, it is still required that they are\nclosed when operations are completed:
import { open } from 'node:fs/promises';\n\nlet file;\ntry {\n file = await open('/open/some/file.txt', 'r');\n const stat = await file.stat();\n // use stat\n} finally {\n await file.close();\n}\n
All callback and promise-based file system APIs (with the exception of\nfs.FSWatcher()) use libuv's threadpool. This can have surprising and negative\nperformance implications for some applications. See the\nUV_THREADPOOL_SIZE documentation for more information.
fs.FSWatcher()
UV_THREADPOOL_SIZE
The following flags are available wherever the flag option takes a\nstring.
flag
'a': Open file for appending.\nThe file is created if it does not exist.
'a'
'ax': Like 'a' but fails if the path exists.
'ax'
'a+': Open file for reading and appending.\nThe file is created if it does not exist.
'a+'
'ax+': Like 'a+' but fails if the path exists.
'ax+'
'as': Open file for appending in synchronous mode.\nThe file is created if it does not exist.
'as'
'as+': Open file for reading and appending in synchronous mode.\nThe file is created if it does not exist.
'as+'
'r': Open file for reading.\nAn exception occurs if the file does not exist.
'r'
'r+': Open file for reading and writing.\nAn exception occurs if the file does not exist.
'r+'
'rs+': Open file for reading and writing in synchronous mode. Instructs\nthe operating system to bypass the local file system cache.
'rs+'
This is primarily useful for opening files on NFS mounts as it allows\nskipping the potentially stale local cache. It has a very real impact on\nI/O performance so using this flag is not recommended unless it is needed.
This doesn't turn fs.open() or fsPromises.open() into a synchronous\nblocking call. If synchronous operation is desired, something like\nfs.openSync() should be used.
'w': Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'w'
'wx': Like 'w' but fails if the path exists.
'wx'
'w+': Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'w+'
'wx+': Like 'w+' but fails if the path exists.
'wx+'
flag can also be a number as documented by open(2); commonly used constants\nare available from fs.constants. On Windows, flags are translated to\ntheir equivalent ones where applicable, e.g. O_WRONLY to FILE_GENERIC_WRITE,\nor O_EXCL|O_CREAT to CREATE_NEW, as accepted by CreateFileW.
FILE_GENERIC_WRITE
O_EXCL|O_CREAT
CREATE_NEW
CreateFileW
The exclusive flag 'x' (O_EXCL flag in open(2)) causes the operation to\nreturn an error if the path already exists. On POSIX, if the path is a symbolic\nlink, using O_EXCL returns an error even if the link is to a path that does\nnot exist. The exclusive flag might not work with network file systems.
'x'
Modifying a file rather than replacing it may require the flag option to be\nset to 'r+' rather than the default 'w'.
The behavior of some flags are platform-specific. As such, opening a directory\non macOS and Linux with the 'a+' flag, as in the example below, will return an\nerror. In contrast, on Windows and FreeBSD, a file descriptor or a FileHandle\nwill be returned.
// macOS and Linux\nfs.open('<directory>', 'a+', (err, fd) => {\n // => [Error: EISDIR: illegal operation on a directory, open <directory>]\n});\n\n// Windows and FreeBSD\nfs.open('<directory>', 'a+', (err, fd) => {\n // => null, <fd>\n});\n
On Windows, opening an existing hidden file using the 'w' flag (either\nthrough fs.open(), fs.writeFile(), or fsPromises.open()) will fail with\nEPERM. Existing hidden files can be opened for writing with the 'r+' flag.
A call to fs.ftruncate() or filehandle.truncate() can be used to reset\nthe file contents.
filehandle.truncate()