{ "source": "doc/api/fs.markdown", "modules": [ { "textRaw": "File System", "name": "fs", "stability": 2, "stabilityText": "Stable", "desc": "
File I/O is provided by simple wrappers around standard POSIX functions. To\nuse this module do require('fs')
. All the methods have asynchronous and\nsynchronous forms.\n\n
The asynchronous form always takes a completion callback as its last argument.\nThe arguments passed to the completion callback depend on the method, but the\nfirst argument is always reserved for an exception. If the operation was\ncompleted successfully, then the first argument will be null
or undefined
.\n\n
When using the synchronous form any exceptions are immediately thrown.\nYou can use try/catch to handle exceptions or allow them to bubble up.\n\n
\nHere is an example of the asynchronous version:\n\n
\nvar fs = require('fs');\n\nfs.unlink('/tmp/hello', function (err) {\n if (err) throw err;\n console.log('successfully deleted /tmp/hello');\n});
\nHere is the synchronous version:\n\n
\nvar fs = require('fs');\n\nfs.unlinkSync('/tmp/hello');\nconsole.log('successfully deleted /tmp/hello');
\nWith the asynchronous methods there is no guaranteed ordering. So the\nfollowing is prone to error:\n\n
\nfs.rename('/tmp/hello', '/tmp/world', function (err) {\n if (err) throw err;\n console.log('renamed complete');\n});\nfs.stat('/tmp/world', function (err, stats) {\n if (err) throw err;\n console.log('stats: ' + JSON.stringify(stats));\n});
\nIt could be that fs.stat
is executed before fs.rename
.\nThe correct way to do this is to chain the callbacks.\n\n
fs.rename('/tmp/hello', '/tmp/world', function (err) {\n if (err) throw err;\n fs.stat('/tmp/world', function (err, stats) {\n if (err) throw err;\n console.log('stats: ' + JSON.stringify(stats));\n });\n});
\nIn busy processes, the programmer is strongly encouraged to use the\nasynchronous versions of these calls. The synchronous versions will block\nthe entire process until they complete--halting all connections.\n\n
\nThe relative path to a filename can be used. Remember, however, that this path\nwill be relative to process.cwd()
.\n\n
Most fs functions let you omit the callback argument. If you do, a default\ncallback is used that rethrows errors. To get a trace to the original call\nsite, set the NODE_DEBUG environment variable:\n\n
\n$ cat script.js\nfunction bad() {\n require('fs').readFile('/');\n}\nbad();\n\n$ env NODE_DEBUG=fs node script.js\nfs.js:66\n throw err;\n ^\nError: EISDIR, read\n at rethrow (fs.js:61:21)\n at maybeCallback (fs.js:79:42)\n at Object.fs.readFile (fs.js:153:18)\n at bad (/path/to/script.js:2:17)\n at Object.<anonymous> (/path/to/script.js:5:1)\n <etc.>
\n",
"methods": [
{
"textRaw": "fs.rename(oldPath, newPath, callback)",
"type": "method",
"name": "rename",
"desc": "Asynchronous rename(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "oldPath" }, { "name": "newPath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.renameSync(oldPath, newPath)", "type": "method", "name": "renameSync", "desc": "Synchronous rename(2). Returns undefined
.\n\n
Asynchronous ftruncate(2). No arguments other than a possible exception are\ngiven to the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "len" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.ftruncateSync(fd, len)", "type": "method", "name": "ftruncateSync", "desc": "Synchronous ftruncate(2). Returns undefined
.\n\n
Asynchronous truncate(2). 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.\n\n
Synchronous truncate(2). Returns undefined
.\n\n
Asynchronous chown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chownSync(path, uid, gid)", "type": "method", "name": "chownSync", "desc": "Synchronous chown(2). Returns undefined
.\n\n
Asynchronous fchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchownSync(fd, uid, gid)", "type": "method", "name": "fchownSync", "desc": "Synchronous fchown(2). Returns undefined
.\n\n
Asynchronous lchown(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "uid" }, { "name": "gid" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchownSync(path, uid, gid)", "type": "method", "name": "lchownSync", "desc": "Synchronous lchown(2). Returns undefined
.\n\n
Asynchronous chmod(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.chmodSync(path, mode)", "type": "method", "name": "chmodSync", "desc": "Synchronous chmod(2). Returns undefined
.\n\n
Asynchronous fchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fchmodSync(fd, mode)", "type": "method", "name": "fchmodSync", "desc": "Synchronous fchmod(2). Returns undefined
.\n\n
Asynchronous lchmod(2). No arguments other than a possible exception\nare given to the completion callback.\n\n
\nOnly available on Mac OS X.\n\n
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "mode" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.lchmodSync(path, mode)", "type": "method", "name": "lchmodSync", "desc": "Synchronous lchmod(2). Returns undefined
.\n\n
Asynchronous stat(2). The callback gets two arguments (err, stats)
where\nstats
is a fs.Stats object. See the fs.Stats\nsection below for more information.\n\n
Asynchronous lstat(2). The callback gets two arguments (err, stats)
where\nstats
is a fs.Stats
object. lstat()
is identical to stat()
, except that if\npath
is a symbolic link, then the link itself is stat-ed, not the file that it\nrefers to.\n\n
Asynchronous fstat(2). The callback gets two arguments (err, stats)
where\nstats
is a fs.Stats
object. fstat()
is identical to stat()
, except that\nthe file to be stat-ed is specified by the file descriptor fd
.\n\n
Synchronous stat(2). Returns an instance of fs.Stats
.\n\n
Synchronous lstat(2). Returns an instance of fs.Stats
.\n\n
Synchronous fstat(2). Returns an instance of fs.Stats
.\n\n
Asynchronous link(2). No arguments other than a possible exception are given to\nthe completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "srcpath" }, { "name": "dstpath" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.linkSync(srcpath, dstpath)", "type": "method", "name": "linkSync", "desc": "Synchronous link(2). Returns undefined
.\n\n
Asynchronous symlink(2). No arguments other than a possible exception are given\nto the completion callback.\nThe type
argument can be set to 'dir'
, 'file'
, or 'junction'
(default\nis 'file'
) and is only available on Windows (ignored on other platforms).\nNote that Windows junction points require the destination path to be absolute. When using\n'junction'
, the destination
argument will automatically be normalized to absolute path.\n\n
Synchronous symlink(2). Returns undefined
.\n\n
Asynchronous readlink(2). The callback gets two arguments (err,\nlinkString)
.\n\n
Synchronous readlink(2). Returns the symbolic link's string value.\n\n
\n", "signatures": [ { "params": [ { "name": "path" } ] } ] }, { "textRaw": "fs.realpath(path[, cache], callback)", "type": "method", "name": "realpath", "desc": "Asynchronous realpath(2). The callback
gets two arguments (err,\nresolvedPath)
. May use process.cwd
to resolve relative paths. cache
is an\nobject literal of mapped paths that can be used to force a specific path\nresolution or avoid additional fs.stat
calls for known real paths.\n\n
Example:\n\n
\nvar cache = {'/etc':'/private/etc'};\nfs.realpath('/etc/passwd', cache, function (err, resolvedPath) {\n if (err) throw err;\n console.log(resolvedPath);\n});
\n",
"signatures": [
{
"params": [
{
"name": "path"
},
{
"name": "cache",
"optional": true
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "fs.realpathSync(path[, cache])",
"type": "method",
"name": "realpathSync",
"desc": "Synchronous realpath(2). Returns the resolved path.\n\n
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "cache", "optional": true } ] } ] }, { "textRaw": "fs.unlink(path, callback)", "type": "method", "name": "unlink", "desc": "Asynchronous unlink(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.unlinkSync(path)", "type": "method", "name": "unlinkSync", "desc": "Synchronous unlink(2). Returns undefined
.\n\n
Asynchronous rmdir(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.rmdirSync(path)", "type": "method", "name": "rmdirSync", "desc": "Synchronous rmdir(2). Returns undefined
.\n\n
Asynchronous mkdir(2). No arguments other than a possible exception are given\nto the completion callback. mode
defaults to 0o777
.\n\n
Synchronous mkdir(2). Returns undefined
.\n\n
Asynchronous readdir(3). Reads the contents of a directory.\nThe callback gets two arguments (err, files)
where files
is an array of\nthe names of the files in the directory excluding '.'
and '..'
.\n\n
Synchronous readdir(3). Returns an array of filenames excluding '.'
and\n'..'
.\n\n
Asynchronous close(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.closeSync(fd)", "type": "method", "name": "closeSync", "desc": "Synchronous close(2). Returns undefined
.\n\n
Asynchronous file open. See open(2). flags
can be:\n\n
'r'
- Open file for reading.\nAn exception occurs if the file does not exist.
'r+'
- Open file for reading and writing.\nAn exception occurs if the file does not exist.
'rs'
- Open file for reading in synchronous mode. Instructs the operating\nsystem to bypass the local file system cache.
This is primarily useful for opening files on NFS mounts as it allows you to\nskip the potentially stale local cache. It has a very real impact on I/O\nperformance so don't use this flag unless you need it.
\nNote that this doesn't turn fs.open()
into a synchronous blocking call.\nIf that's what you want then you should be using fs.openSync()
'rs+'
- Open file for reading and writing, telling the OS to open it\nsynchronously. See notes for 'rs'
about using this with caution.
'w'
- Open file for writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'wx'
- Like 'w'
but fails if path
exists.
'w+'
- Open file for reading and writing.\nThe file is created (if it does not exist) or truncated (if it exists).
'wx+'
- Like 'w+'
but fails if path
exists.
'a'
- Open file for appending.\nThe file is created if it does not exist.
'ax'
- Like 'a'
but fails if path
exists.
'a+'
- Open file for reading and appending.\nThe file is created if it does not exist.
'ax+'
- Like 'a+'
but fails if path
exists.
mode
sets the file mode (permission and sticky bits), but only if the file was\ncreated. It defaults to 0666
, readable and writeable.\n\n
The callback gets two arguments (err, fd)
.\n\n
The exclusive flag 'x'
(O_EXCL
flag in open(2)) ensures that path
is newly\ncreated. On POSIX systems, path
is considered to exist even if it is a symlink\nto a non-existent file. The exclusive flag may or may not work with network file\nsystems.\n\n
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.\n\n
\n", "signatures": [ { "params": [ { "name": "path" }, { "name": "flags" }, { "name": "mode", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.openSync(path, flags[, mode])", "type": "method", "name": "openSync", "desc": "Synchronous version of fs.open()
. Returns an integer representing the file\ndescriptor.\n\n
Change file timestamps of the file referenced by the supplied path.\n\n
\nNote: the arguments atime
and mtime
of the following related functions does\nfollow the below rules:\n\n
NaN
or Infinity
, the value would get converted to\nDate.now()
.Synchronous version of fs.utimes()
. Returns undefined
.\n\n\n
Change the file timestamps of a file referenced by the supplied file\ndescriptor.\n\n
\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "atime" }, { "name": "mtime" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.futimesSync(fd, atime, mtime)", "type": "method", "name": "futimesSync", "desc": "Synchronous version of fs.futimes()
. Returns undefined
.\n\n
Asynchronous fsync(2). No arguments other than a possible exception are given\nto the completion callback.\n\n
\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "callback" } ] } ] }, { "textRaw": "fs.fsyncSync(fd)", "type": "method", "name": "fsyncSync", "desc": "Synchronous fsync(2). Returns undefined
.\n\n
Write buffer
to the file specified by fd
.\n\n
offset
and length
determine the part of the buffer to be written.\n\n
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).\n\n
The callback will be given three arguments (err, written, buffer)
where\nwritten
specifies how many bytes were written from buffer
.\n\n
Note that it is unsafe to use fs.write
multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream
is strongly recommended.\n\n
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.\n\n
\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "buffer" }, { "name": "offset" }, { "name": "length" }, { "name": "position", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.write(fd, data[, position[, encoding]], callback)", "type": "method", "name": "write", "desc": "Write data
to the file specified by fd
. If data
is not a Buffer instance\nthen the value will be coerced to a string.\n\n
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).\n\n
encoding
is the expected string encoding.\n\n
The callback will receive the arguments (err, written, string)
where written
\nspecifies how many bytes the passed string required to be written. Note that\nbytes written is not the same as string characters. See\nBuffer.byteLength.\n\n
Unlike when writing buffer
, the entire string must be written. No substring\nmay be specified. This is because the byte offset of the resulting data may not\nbe the same as the string offset.\n\n
Note that it is unsafe to use fs.write
multiple times on the same file\nwithout waiting for the callback. For this scenario,\nfs.createWriteStream
is strongly recommended.\n\n
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.\n\n
\n", "signatures": [ { "params": [ { "name": "fd" }, { "name": "data" }, { "name": "position" }, { "name": "encoding]", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "fs.writeSync(fd, buffer, offset, length[, position])", "type": "method", "name": "writeSync", "desc": "Synchronous versions of fs.write()
. Returns the number of bytes written.\n\n
Synchronous versions of fs.write()
. Returns the number of bytes written.\n\n
Read data from the file specified by fd
.\n\n
buffer
is the buffer that the data will be written to.\n\n
offset
is the offset in the buffer to start writing at.\n\n
length
is an integer specifying the number of bytes to read.\n\n
position
is an integer specifying where to begin reading from in the file.\nIf position
is null
, data will be read from the current file position.\n\n
The callback is given the three arguments, (err, bytesRead, buffer)
.\n\n
Synchronous version of fs.read
. Returns the number of bytesRead
.\n\n
Asynchronously reads the entire contents of a file. Example:\n\n
\nfs.readFile('/etc/passwd', function (err, data) {\n if (err) throw err;\n console.log(data);\n});
\nThe callback is passed two arguments (err, data)
, where data
is the\ncontents of the file.\n\n
If no encoding is specified, then the raw buffer is returned.\n\n
\nIf options
is a string, then it specifies the encoding. Example:\n\n
fs.readFile('/etc/passwd', 'utf8', callback);
\n"
},
{
"textRaw": "fs.readFileSync(filename[, options])",
"type": "method",
"name": "readFileSync",
"desc": "Synchronous version of fs.readFile
. Returns the contents of the filename
.\n\n
If the encoding
option is specified then this function returns a\nstring. Otherwise it returns a buffer.\n\n\n
Asynchronously writes data to a file, replacing the file if it already exists.\ndata
can be a string or a buffer.\n\n
The encoding
option is ignored if data
is a buffer. It defaults\nto 'utf8'
.\n\n
Example:\n\n
\nfs.writeFile('message.txt', 'Hello Node.js', function (err) {\n if (err) throw err;\n console.log('It\\'s saved!');\n});
\nIf options
is a string, then it specifies the encoding. Example:\n\n
fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
\n"
},
{
"textRaw": "fs.writeFileSync(filename, data[, options])",
"type": "method",
"name": "writeFileSync",
"desc": "The synchronous version of fs.writeFile
. Returns undefined
.\n\n
Asynchronously append data to a file, creating the file if it does not yet exist.\ndata
can be a string or a buffer.\n\n
Example:\n\n
\nfs.appendFile('message.txt', 'data to append', function (err) {\n if (err) throw err;\n console.log('The "data to append" was appended to file!');\n});
\nIf options
is a string, then it specifies the encoding. Example:\n\n
fs.appendFile('message.txt', 'data to append', 'utf8', callback);
\n"
},
{
"textRaw": "fs.appendFileSync(filename, data[, options])",
"type": "method",
"name": "appendFileSync",
"desc": "The synchronous version of fs.appendFile
. Returns undefined
.\n\n
Watch for changes on filename
. The callback listener
will be called each\ntime the file is accessed.\n\n
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. The default is\n{ persistent: true, interval: 5007 }
.\n\n
The listener
gets two arguments the current stat object and the previous\nstat object:\n\n
fs.watchFile('message.text', function (curr, prev) {\n console.log('the current mtime is: ' + curr.mtime);\n console.log('the previous mtime was: ' + prev.mtime);\n});
\nThese stat objects are instances of fs.Stat
.\n\n
If you want to be notified when the file was modified, not just accessed,\nyou need to compare curr.mtime
and prev.mtime
.\n\n
Note: when an fs.watchFile
operation results in an ENOENT
error, it will\n invoke the listener once, with all the fields zeroed (or, for dates, the Unix\n Epoch). In Windows, blksize
and blocks
fields will be undefined
, instead\n of zero. If the file is created later on, the listener will be called again,\n with the latest stat objects. This is a change in functionality since v0.10.\n\n
Note: fs.watch
is more efficient than fs.watchFile
and fs.unwatchFile
.\nfs.watch
should be used instead of fs.watchFile
and fs.unwatchFile
\nwhen possible.\n\n
Stop watching for changes on filename
. If listener
is specified, only that\nparticular listener is removed. Otherwise, all listeners are removed and you\nhave effectively stopped watching filename
.\n\n
Calling fs.unwatchFile()
with a filename that is not being watched is a\nno-op, not an error.\n\n
Note: fs.watch
is more efficient than fs.watchFile
and fs.unwatchFile
.\nfs.watch
should be used instead of fs.watchFile
and fs.unwatchFile
\nwhen possible.\n\n
Watch for changes on filename
, where filename
is either a file or a\ndirectory. The returned object is a fs.FSWatcher.\n\n
The second argument is optional. The options
if provided should be an object.\nThe supported boolean members are persistent
and recursive
. persistent
\nindicates whether the process should continue to run as long as files are being\nwatched. recursive
indicates whether all subdirectories should be watched, or\nonly the current directory. This applies when a directory is specified, and only\non supported platforms (See Caveats below).\n\n
The default is { persistent: true, recursive: false }
.\n\n
The listener callback gets two arguments (event, filename)
. event
is either\n'rename' or 'change', and filename
is the name of the file which triggered\nthe event.\n\n
The fs.watch
API is not 100% consistent across platforms, and is\nunavailable in some situations.\n\n
The recursive option is only supported on OS X and Windows.\n\n
\n", "miscs": [ { "textRaw": "Availability", "name": "Availability", "type": "misc", "desc": "This feature depends on the underlying operating system providing a way\nto be notified of filesystem changes.\n\n
\ninotify
.kqueue
.kqueue
for files and 'FSEvents' for directories.event ports
.ReadDirectoryChangesW
.If the underlying functionality is not available for some reason, then\nfs.watch
will not be able to function. For example, watching files or\ndirectories on network file systems (NFS, SMB, etc.) often doesn't work\nreliably or at all.\n\n
You can still use fs.watchFile
, which uses stat polling, but it is slower and\nless reliable.\n\n
Providing filename
argument in the callback is only supported on Linux and \nWindows. Even on supported platforms, filename
is not always guaranteed to\nbe provided. Therefore, don't assume that filename
argument is always\nprovided in the callback, and have some fallback logic if it is null.\n\n
fs.watch('somedir', function (event, filename) {\n console.log('event is: ' + event);\n if (filename) {\n console.log('filename provided: ' + filename);\n } else {\n console.log('filename not provided');\n }\n});
\n"
}
]
}
],
"signatures": [
{
"params": [
{
"name": "filename"
},
{
"name": "options",
"optional": true
},
{
"name": "listener",
"optional": true
}
]
}
]
},
{
"textRaw": "fs.exists(path, callback)",
"type": "method",
"name": "exists",
"stability": 0,
"stabilityText": "Deprecated: Use [fs.stat][] or [fs.access][] instead.",
"desc": "Test whether or not the given path exists by checking with the file system.\nThen call the callback
argument with either true or false. Example:\n\n
fs.exists('/etc/passwd', function (exists) {\n console.log(exists ? "it's there" : 'no passwd!');\n});
\nfs.exists()
should not be used to check if a file exists before calling\nfs.open()
. Doing so introduces a race condition since other processes may\nchange the file's state between the two calls. Instead, user code should\ncall fs.open()
directly and handle the error raised if the file is\nnon-existent.\n\n
Synchronous version of fs.exists
.\nReturns true
if the file exists, false
otherwise.\n\n
Stability: 0 - Deprecated: Use [fs.statSync][] or [fs.accessSync][] instead.
\n",
"signatures": [
{
"params": [
{
"name": "path"
}
]
}
]
},
{
"textRaw": "fs.access(path[, mode], callback)",
"type": "method",
"name": "access",
"desc": "Tests a user's permissions for the file specified by path
. mode
is an\noptional integer that specifies the accessibility checks to be performed. The\nfollowing constants define the possible values of mode
. It is possible to\ncreate a mask consisting of the bitwise OR of two or more values.\n\n
fs.F_OK
- File is visible to the calling process. This is useful for\ndetermining if a file exists, but says nothing about rwx
permissions.\nDefault if no mode
is specified.fs.R_OK
- File can be read by the calling process.fs.W_OK
- File can be written by the calling process.fs.X_OK
- File can be executed by the calling process. This has no effect\non Windows (will behave like fs.F_OK
).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 populated. The following example checks if the file\n/etc/passwd
can be read and written by the current process.\n\n
fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) {\n console.log(err ? 'no access!' : 'can read/write');\n});
\n",
"signatures": [
{
"params": [
{
"name": "path"
},
{
"name": "mode",
"optional": true
},
{
"name": "callback"
}
]
}
]
},
{
"textRaw": "fs.accessSync(path[, mode])",
"type": "method",
"name": "accessSync",
"desc": "Synchronous version of fs.access
. This throws if any accessibility checks\nfail, and does nothing otherwise.\n\n
Returns a new ReadStream object (See Readable Stream
).\n\n
Be aware that, unlike the default value set for highWaterMark
on a\nreadable stream (16 kb), the stream returned by this method has a\ndefault value of 64 kb for the same parameter.\n\n
options
is an object or string with the following defaults:\n\n
{ flags: 'r',\n encoding: null,\n fd: null,\n mode: 0o666,\n autoClose: true\n}
\noptions
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 at 0. The encoding
can be 'utf8'
, 'ascii'
, or 'base64'
.\n\n
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 emitted.\n\n
If autoClose
is false, then the file descriptor won't be closed, even if\nthere's an error. It is your responsibility to close it and make sure\nthere's no file descriptor leak. If autoClose
is set to true (default\nbehavior), on error
or end
the file descriptor will be closed\nautomatically.\n\n
mode
sets the file mode (permission and sticky bits), but only if the\nfile was created.\n\n
An example to read the last 10 bytes of a file which is 100 bytes long:\n\n
\nfs.createReadStream('sample.txt', {start: 90, end: 99});
\nIf options
is a string, then it specifies the encoding.\n\n
Returns a new WriteStream object (See Writable Stream
).\n\n
options
is an object or string with the following defaults:\n\n
{ flags: 'w',\n defaultEncoding: 'utf8',\n fd: null,\n mode: 0o666 }
\noptions
may also include a start
option to allow writing data at\nsome position past the beginning of the file. Modifying a file rather\nthan replacing it may require a flags
mode of r+
rather than the\ndefault mode w
. The defaultEncoding
can be 'utf8'
, 'ascii'
, binary
,\nor 'base64'
.\n\n
Like ReadStream
above, if fd
is specified, WriteStream
will ignore the\npath
argument and will use the specified file descriptor. This means that no\nopen
event will be emitted.\n\n
If options
is a string, then it specifies the encoding.\n\n
Objects returned from fs.stat()
, fs.lstat()
and fs.fstat()
and their\nsynchronous counterparts are of this type.\n\n
stats.isFile()
stats.isDirectory()
stats.isBlockDevice()
stats.isCharacterDevice()
stats.isSymbolicLink()
(only valid with fs.lstat()
)stats.isFIFO()
stats.isSocket()
For a regular file util.inspect(stats)
would return a string very\nsimilar to this:\n\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 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 }
\nPlease note that atime
, mtime
, birthtime
, and ctime
are\ninstances of [Date][MDN-Date] object and to compare the values of\nthese objects you should use appropriate methods. For most general\nuses [getTime()][MDN-Date-getTime] will return the number of\nmilliseconds elapsed since 1 January 1970 00:00:00 UTC and this\ninteger should be sufficient for any comparison, however there are\nadditional methods which can be used for displaying fuzzy information.\nMore details can be found in the [MDN JavaScript Reference][MDN-Date]\npage.\n\n
The times in the stat object have the following semantics:\n\n
\natime
"Access Time" - Time when file data last accessed. Changed\nby the mknod(2)
, utimes(2)
, and read(2)
system calls.mtime
"Modified Time" - Time when file data last modified.\nChanged by the mknod(2)
, utimes(2)
, and write(2)
system calls.ctime
"Change Time" - Time when file status was last changed\n(inode data modification). Changed by the chmod(2)
, chown(2)
,\nlink(2)
, mknod(2)
, rename(2)
, unlink(2)
, utimes(2)
,\nread(2)
, and write(2)
system calls.birthtime
"Birth Time" - Time of file creation. Set once when the\nfile is created. On filesystems where birthtime is not available,\nthis field may instead hold either the ctime
or\n1970-01-01T00:00Z
(ie, unix epoch timestamp 0
). On Darwin and\nother FreeBSD variants, also set if the atime
is explicitly set to\nan earlier value than the current birthtime
using the utimes(2)
\nsystem call.Prior to Node v0.12, the ctime
held the birthtime
on Windows\nsystems. Note that as of v0.12, ctime
is not "creation time", and\non Unix systems, it never was.\n\n
ReadStream
is a Readable Stream.\n\n
Emitted when the ReadStream's file is opened.\n\n\n
\n" } ] }, { "textRaw": "Class: fs.WriteStream", "type": "class", "name": "fs.WriteStream", "desc": "WriteStream
is a Writable Stream.\n\n
Emitted when the WriteStream's file is opened.\n\n
\n" } ], "properties": [ { "textRaw": "file.bytesWritten", "name": "bytesWritten", "desc": "The number of bytes written so far. Does not include data that is still queued\nfor writing.\n\n
\n" } ] }, { "textRaw": "Class: fs.FSWatcher", "type": "class", "name": "fs.FSWatcher", "desc": "Objects returned from fs.watch()
are of this type.\n\n
Stop watching for changes on the given fs.FSWatcher
.\n\n
Emitted when something changes in a watched directory or file.\nSee more details in fs.watch.\n\n
\n" }, { "textRaw": "Event: 'error'", "type": "event", "name": "error", "params": [], "desc": "Emitted when an error occurs.\n\n\n
\n" } ] } ], "type": "module", "displayName": "fs" } ] }