diff --git a/doc/api/fs.markdown b/doc/api/fs.markdown index c9fd8466811c..e3e76221e32b 100644 --- a/doc/api/fs.markdown +++ b/doc/api/fs.markdown @@ -85,33 +85,71 @@ site, set the NODE_DEBUG environment variable: -## fs.rename(oldPath, newPath, callback) +## fs.access(path[, mode], callback) -Asynchronous rename(2). No arguments other than a possible exception are given -to the completion callback. +Tests a user's permissions for the file specified by `path`. `mode` is an +optional integer that specifies the accessibility checks to be performed. The +following constants define the possible values of `mode`. It is possible to +create a mask consisting of the bitwise OR of two or more values. -## fs.renameSync(oldPath, newPath) +- `fs.F_OK` - File is visible to the calling process. This is useful for +determining if a file exists, but says nothing about `rwx` permissions. +Default 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 +on Windows (will behave like `fs.F_OK`). -Synchronous rename(2). Returns `undefined`. +The final argument, `callback`, is a callback function that is invoked with +a possible error argument. If any of the accessibility checks fail, the error +argument will be populated. The following example checks if the file +`/etc/passwd` can be read and written by the current process. -## fs.ftruncate(fd, len, callback) + fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) { + console.log(err ? 'no access!' : 'can read/write'); + }); -Asynchronous ftruncate(2). No arguments other than a possible exception are -given to the completion callback. +## fs.accessSync(path[, mode]) -## fs.ftruncateSync(fd, len) +Synchronous version of `fs.access`. This throws if any accessibility checks +fail, and does nothing otherwise. -Synchronous ftruncate(2). Returns `undefined`. +## fs.appendFile(filename, data[, options], callback) -## fs.truncate(path, len, callback) +* `filename` {String} +* `data` {String | Buffer} +* `options` {Object | String} + * `encoding` {String | Null} default = `'utf8'` + * `mode` {Number} default = `0o666` + * `flag` {String} default = `'a'` +* `callback` {Function} -Asynchronous truncate(2). No arguments other than a possible exception are -given to the completion callback. A file descriptor can also be passed as the -first argument. In this case, `fs.ftruncate()` is called. +Asynchronously append data to a file, creating the file if it does not yet exist. +`data` can be a string or a buffer. -## fs.truncateSync(path, len) +Example: -Synchronous truncate(2). Returns `undefined`. + fs.appendFile('message.txt', 'data to append', function (err) { + if (err) throw err; + console.log('The "data to append" was appended to file!'); + }); + +If `options` is a string, then it specifies the encoding. Example: + + fs.appendFile('message.txt', 'data to append', 'utf8', callback); + +## fs.appendFileSync(filename, data[, options]) + +The synchronous version of `fs.appendFile`. Returns `undefined`. + +## fs.chmod(path, mode, callback) + +Asynchronous chmod(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.chmodSync(path, mode) + +Synchronous chmod(2). Returns `undefined`. ## fs.chown(path, uid, gid, callback) @@ -122,180 +160,210 @@ to the completion callback. Synchronous chown(2). Returns `undefined`. -## fs.fchown(fd, uid, gid, callback) +## fs.close(fd, callback) -Asynchronous fchown(2). No arguments other than a possible exception are given +Asynchronous close(2). No arguments other than a possible exception are given to the completion callback. -## fs.fchownSync(fd, uid, gid) - -Synchronous fchown(2). Returns `undefined`. +## fs.closeSync(fd) -## fs.lchown(path, uid, gid, callback) +Synchronous close(2). Returns `undefined`. -Asynchronous lchown(2). No arguments other than a possible exception are given -to the completion callback. +## fs.createReadStream(path[, options]) -## fs.lchownSync(path, uid, gid) +Returns a new ReadStream object (See `Readable Stream`). -Synchronous lchown(2). Returns `undefined`. +Be aware that, unlike the default value set for `highWaterMark` on a +readable stream (16 kb), the stream returned by this method has a +default value of 64 kb for the same parameter. -## fs.chmod(path, mode, callback) +`options` is an object or string with the following defaults: -Asynchronous chmod(2). No arguments other than a possible exception are given -to the completion callback. + { flags: 'r', + encoding: null, + fd: null, + mode: 0o666, + autoClose: true + } -## fs.chmodSync(path, mode) +`options` can include `start` and `end` values to read a range of bytes from +the file instead of the entire file. Both `start` and `end` are inclusive and +start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`. -Synchronous chmod(2). Returns `undefined`. +If `fd` is specified, `ReadStream` will ignore the `path` argument and will use +the specified file descriptor. This means that no `open` event will be emitted. -## fs.fchmod(fd, mode, callback) +If `autoClose` is false, then the file descriptor won't be closed, even if +there's an error. It is your responsibility to close it and make sure +there's no file descriptor leak. If `autoClose` is set to true (default +behavior), on `error` or `end` the file descriptor will be closed +automatically. -Asynchronous fchmod(2). No arguments other than a possible exception -are given to the completion callback. +`mode` sets the file mode (permission and sticky bits), but only if the +file was created. -## fs.fchmodSync(fd, mode) +An example to read the last 10 bytes of a file which is 100 bytes long: -Synchronous fchmod(2). Returns `undefined`. + fs.createReadStream('sample.txt', {start: 90, end: 99}); -## fs.lchmod(path, mode, callback) +If `options` is a string, then it specifies the encoding. -Asynchronous lchmod(2). No arguments other than a possible exception -are given to the completion callback. +## fs.createWriteStream(path[, options]) -Only available on Mac OS X. +Returns a new WriteStream object (See `Writable Stream`). -## fs.lchmodSync(path, mode) +`options` is an object or string with the following defaults: -Synchronous lchmod(2). Returns `undefined`. + { flags: 'w', + defaultEncoding: 'utf8', + fd: null, + mode: 0o666 } -## fs.stat(path, callback) +`options` may also include a `start` option to allow writing data at +some position past the beginning of the file. Modifying a file rather +than replacing it may require a `flags` mode of `r+` rather than the +default mode `w`. The `defaultEncoding` can be `'utf8'`, `'ascii'`, `binary`, +or `'base64'`. -Asynchronous stat(2). The callback gets two arguments `(err, stats)` where -`stats` is a [fs.Stats](#fs_class_fs_stats) object. See the [fs.Stats](#fs_class_fs_stats) -section below for more information. +Like `ReadStream` above, if `fd` is specified, `WriteStream` will ignore the +`path` argument and will use the specified file descriptor. This means that no +`open` event will be emitted. -## fs.lstat(path, callback) +If `options` is a string, then it specifies the encoding. -Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where -`stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if -`path` is a symbolic link, then the link itself is stat-ed, not the file that it -refers to. +## fs.exists(path, callback) -## fs.fstat(fd, callback) +`fs.exists()` is **deprecated**. For supported alternatives please check out +[`fs.stat`](fs.html#fs_fs_stat_path_callback) or +[`fs.access`](fs.html#fs_fs_access_path_mode_callback). -Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where -`stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that -the file to be stat-ed is specified by the file descriptor `fd`. +Test whether or not the given path exists by checking with the file system. +Then call the `callback` argument with either true or false. Example: -## fs.statSync(path) + fs.exists('/etc/passwd', function (exists) { + console.log(exists ? "it's there" : 'no passwd!'); + }); -Synchronous stat(2). Returns an instance of `fs.Stats`. +`fs.exists()` is an anachronism and exists only for historical reasons. +There should almost never be a reason to use it in your own code. -## fs.lstatSync(path) +In particular, checking if a file exists before opening it is an anti-pattern +that leaves you vulnerable to race conditions: another process may remove the +file between the calls to `fs.exists()` and `fs.open()`. Just open the file +and handle the error when it's not there. -Synchronous lstat(2). Returns an instance of `fs.Stats`. +## fs.existsSync(path) -## fs.fstatSync(fd) +Synchronous version of [`fs.exists`](fs.html#fs_fs_exists_path_callback). +Returns `true` if the file exists, `false` otherwise. -Synchronous fstat(2). Returns an instance of `fs.Stats`. +`fs.existsSync()` is **deprecated**. For supported alternatives please check +out [`fs.statSync`](fs.html#fs_fs_statsync_path) or +[`fs.accessSync`](fs.html#fs_fs_accesssync_path_mode). -## fs.link(srcpath, dstpath, callback) +## fs.fchmod(fd, mode, callback) -Asynchronous link(2). No arguments other than a possible exception are given to -the completion callback. +Asynchronous fchmod(2). No arguments other than a possible exception +are given to the completion callback. -## fs.linkSync(srcpath, dstpath) +## fs.fchmodSync(fd, mode) -Synchronous link(2). Returns `undefined`. +Synchronous fchmod(2). Returns `undefined`. -## fs.symlink(destination, path[, type], callback) +## fs.fchown(fd, uid, gid, callback) -Asynchronous symlink(2). No arguments other than a possible exception are given +Asynchronous fchown(2). No arguments other than a possible exception are given to the completion callback. -The `type` argument can be set to `'dir'`, `'file'`, or `'junction'` (default -is `'file'`) and is only available on Windows (ignored on other platforms). -Note that Windows junction points require the destination path to be absolute. When using -`'junction'`, the `destination` argument will automatically be normalized to absolute path. -## fs.symlinkSync(destination, path[, type]) +## fs.fchownSync(fd, uid, gid) -Synchronous symlink(2). Returns `undefined`. +Synchronous fchown(2). Returns `undefined`. -## fs.readlink(path, callback) +## fs.fstat(fd, callback) -Asynchronous readlink(2). The callback gets two arguments `(err, -linkString)`. +Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where +`stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that +the file to be stat-ed is specified by the file descriptor `fd`. -## fs.readlinkSync(path) +## fs.fstatSync(fd) -Synchronous readlink(2). Returns the symbolic link's string value. +Synchronous fstat(2). Returns an instance of `fs.Stats`. -## fs.realpath(path[, cache], callback) +## fs.fsync(fd, callback) -Asynchronous realpath(2). The `callback` gets two arguments `(err, -resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an -object literal of mapped paths that can be used to force a specific path -resolution or avoid additional `fs.stat` calls for known real paths. +Asynchronous fsync(2). No arguments other than a possible exception are given +to the completion callback. -Example: +## fs.fsyncSync(fd) - var cache = {'/etc':'/private/etc'}; - fs.realpath('/etc/passwd', cache, function (err, resolvedPath) { - if (err) throw err; - console.log(resolvedPath); - }); +Synchronous fsync(2). Returns `undefined`. -## fs.realpathSync(path[, cache]) +## fs.ftruncate(fd, len, callback) -Synchronous realpath(2). Returns the resolved path. +Asynchronous ftruncate(2). No arguments other than a possible exception are +given to the completion callback. -## fs.unlink(path, callback) +## fs.ftruncateSync(fd, len) -Asynchronous unlink(2). No arguments other than a possible exception are given -to the completion callback. +Synchronous ftruncate(2). Returns `undefined`. -## fs.unlinkSync(path) +## fs.futimes(fd, atime, mtime, callback) -Synchronous unlink(2). Returns `undefined`. +Change the file timestamps of a file referenced by the supplied file +descriptor. -## fs.rmdir(path, callback) +## fs.futimesSync(fd, atime, mtime) -Asynchronous rmdir(2). No arguments other than a possible exception are given +Synchronous version of `fs.futimes()`. Returns `undefined`. + +## fs.lchmod(path, mode, callback) + +Asynchronous lchmod(2). No arguments other than a possible exception +are given to the completion callback. + +Only available on Mac OS X. + +## fs.lchmodSync(path, mode) + +Synchronous lchmod(2). Returns `undefined`. + +## fs.lchown(path, uid, gid, callback) + +Asynchronous lchown(2). No arguments other than a possible exception are given to the completion callback. -## fs.rmdirSync(path) +## fs.lchownSync(path, uid, gid) -Synchronous rmdir(2). Returns `undefined`. +Synchronous lchown(2). Returns `undefined`. -## fs.mkdir(path[, mode], callback) +## fs.link(srcpath, dstpath, callback) -Asynchronous mkdir(2). No arguments other than a possible exception are given -to the completion callback. `mode` defaults to `0o777`. +Asynchronous link(2). No arguments other than a possible exception are given to +the completion callback. -## fs.mkdirSync(path[, mode]) +## fs.linkSync(srcpath, dstpath) -Synchronous mkdir(2). Returns `undefined`. +Synchronous link(2). Returns `undefined`. -## fs.readdir(path, callback) +## fs.lstat(path, callback) -Asynchronous readdir(3). Reads the contents of a directory. -The callback gets two arguments `(err, files)` where `files` is an array of -the names of the files in the directory excluding `'.'` and `'..'`. +Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where +`stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if +`path` is a symbolic link, then the link itself is stat-ed, not the file that it +refers to. -## fs.readdirSync(path) +## fs.lstatSync(path) -Synchronous readdir(3). Returns an array of filenames excluding `'.'` and -`'..'`. +Synchronous lstat(2). Returns an instance of `fs.Stats`. -## fs.close(fd, callback) +## fs.mkdir(path[, mode], callback) -Asynchronous close(2). No arguments other than a possible exception are given -to the completion callback. +Asynchronous mkdir(2). No arguments other than a possible exception are given +to the completion callback. `mode` defaults to `0o777`. -## fs.closeSync(fd) +## fs.mkdirSync(path[, mode]) -Synchronous close(2). Returns `undefined`. +Synchronous mkdir(2). Returns `undefined`. ## fs.open(path, flags[, mode], callback) @@ -333,113 +401,31 @@ The file is created (if it does not exist) or truncated (if it exists). * `'a'` - Open file for appending. The file is created if it does not exist. -* `'ax'` - Like `'a'` but fails if `path` exists. - -* `'a+'` - Open file for reading and appending. -The 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 -created. It defaults to `0666`, readable and writeable. - -The callback gets two arguments `(err, fd)`. - -The exclusive flag `'x'` (`O_EXCL` flag in open(2)) ensures that `path` is newly -created. On POSIX systems, `path` is considered to exist even if it is a symlink -to a non-existent file. The exclusive flag may or may not work with network file -systems. - -On Linux, positional writes don't work when the file is opened in append mode. -The kernel ignores the position argument and always appends the data to -the end of the file. - -## fs.openSync(path, flags[, mode]) - -Synchronous version of `fs.open()`. Returns an integer representing the file -descriptor. - -## fs.utimes(path, atime, mtime, callback) - -Change file timestamps of the file referenced by the supplied path. - -## fs.utimesSync(path, atime, mtime) - -Synchronous version of `fs.utimes()`. Returns `undefined`. - - -## fs.futimes(fd, atime, mtime, callback) - -Change the file timestamps of a file referenced by the supplied file -descriptor. - -## fs.futimesSync(fd, atime, mtime) - -Synchronous version of `fs.futimes()`. Returns `undefined`. - -## fs.fsync(fd, callback) - -Asynchronous fsync(2). No arguments other than a possible exception are given -to the completion callback. - -## fs.fsyncSync(fd) - -Synchronous fsync(2). Returns `undefined`. - -## fs.write(fd, buffer, offset, length[, position], callback) - -Write `buffer` to the file specified by `fd`. - -`offset` and `length` determine the part of the buffer to be written. - -`position` refers to the offset from the beginning of the file where this data -should be written. If `typeof position !== 'number'`, the data will be written -at the current position. See pwrite(2). - -The callback will be given three arguments `(err, written, buffer)` where -`written` specifies how many _bytes_ were written from `buffer`. - -Note that it is unsafe to use `fs.write` multiple times on the same file -without waiting for the callback. For this scenario, -`fs.createWriteStream` is strongly recommended. - -On Linux, positional writes don't work when the file is opened in append mode. -The kernel ignores the position argument and always appends the data to -the end of the file. - -## fs.write(fd, data[, position[, encoding]], callback) - -Write `data` to the file specified by `fd`. If `data` is not a Buffer instance -then the value will be coerced to a string. - -`position` refers to the offset from the beginning of the file where this data -should be written. If `typeof position !== 'number'` the data will be written at -the current position. See pwrite(2). +* `'ax'` - Like `'a'` but fails if `path` exists. -`encoding` is the expected string encoding. +* `'a+'` - Open file for reading and appending. +The file is created if it does not exist. -The callback will receive the arguments `(err, written, string)` where `written` -specifies how many _bytes_ the passed string required to be written. Note that -bytes written is not the same as string characters. See -[Buffer.byteLength](buffer.html#buffer_class_method_buffer_bytelength_string_encoding). +* `'ax+'` - Like `'a+'` but fails if `path` exists. -Unlike when writing `buffer`, the entire string must be written. No substring -may be specified. This is because the byte offset of the resulting data may not -be the same as the string offset. +`mode` sets the file mode (permission and sticky bits), but only if the file was +created. It defaults to `0666`, readable and writeable. -Note that it is unsafe to use `fs.write` multiple times on the same file -without waiting for the callback. For this scenario, -`fs.createWriteStream` is strongly recommended. +The callback gets two arguments `(err, fd)`. + +The exclusive flag `'x'` (`O_EXCL` flag in open(2)) ensures that `path` is newly +created. On POSIX systems, `path` is considered to exist even if it is a symlink +to a non-existent file. The exclusive flag may or may not work with network file +systems. On Linux, positional writes don't work when the file is opened in append mode. The kernel ignores the position argument and always appends the data to the end of the file. -## fs.writeSync(fd, buffer, offset, length[, position]) - -## fs.writeSync(fd, data[, position[, encoding]]) +## fs.openSync(path, flags[, mode]) -Synchronous versions of `fs.write()`. Returns the number of bytes written. +Synchronous version of `fs.open()`. Returns an integer representing the file +descriptor. ## fs.read(fd, buffer, offset, length, position, callback) @@ -460,6 +446,17 @@ The callback is given the three arguments, `(err, bytesRead, buffer)`. Synchronous version of `fs.read`. Returns the number of `bytesRead`. +## fs.readdir(path, callback) + +Asynchronous readdir(3). Reads the contents of a directory. +The callback gets two arguments `(err, files)` where `files` is an array of +the names of the files in the directory excluding `'.'` and `'..'`. + +## fs.readdirSync(path) + +Synchronous readdir(3). Returns an array of filenames excluding `'.'` and +`'..'`. + ## fs.readFile(filename[, options], callback) * `filename` {String} @@ -493,64 +490,183 @@ If the `encoding` option is specified then this function returns a string. Otherwise it returns a buffer. -## fs.writeFile(filename, data[, options], callback) +## fs.readlink(path, callback) -* `filename` {String} -* `data` {String | Buffer} -* `options` {Object | String} - * `encoding` {String | Null} default = `'utf8'` - * `mode` {Number} default = `0o666` - * `flag` {String} default = `'w'` -* `callback` {Function} +Asynchronous readlink(2). The callback gets two arguments `(err, +linkString)`. -Asynchronously writes data to a file, replacing the file if it already exists. -`data` can be a string or a buffer. +## fs.readlinkSync(path) -The `encoding` option is ignored if `data` is a buffer. It defaults -to `'utf8'`. +Synchronous readlink(2). Returns the symbolic link's string value. + +## fs.realpath(path[, cache], callback) + +Asynchronous realpath(2). The `callback` gets two arguments `(err, +resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an +object literal of mapped paths that can be used to force a specific path +resolution or avoid additional `fs.stat` calls for known real paths. Example: - fs.writeFile('message.txt', 'Hello io.js', function (err) { + var cache = {'/etc':'/private/etc'}; + fs.realpath('/etc/passwd', cache, function (err, resolvedPath) { if (err) throw err; - console.log('It\'s saved!'); + console.log(resolvedPath); }); -If `options` is a string, then it specifies the encoding. Example: +## fs.realpathSync(path[, cache]) - fs.writeFile('message.txt', 'Hello io.js', 'utf8', callback); +Synchronous realpath(2). Returns the resolved path. -## fs.writeFileSync(filename, data[, options]) +## fs.rename(oldPath, newPath, callback) -The synchronous version of `fs.writeFile`. Returns `undefined`. +Asynchronous rename(2). No arguments other than a possible exception are given +to the completion callback. -## fs.appendFile(filename, data[, options], callback) +## fs.renameSync(oldPath, newPath) -* `filename` {String} -* `data` {String | Buffer} -* `options` {Object | String} - * `encoding` {String | Null} default = `'utf8'` - * `mode` {Number} default = `0o666` - * `flag` {String} default = `'a'` -* `callback` {Function} +Synchronous rename(2). Returns `undefined`. -Asynchronously append data to a file, creating the file if it does not yet exist. -`data` can be a string or a buffer. +## fs.rmdir(path, callback) -Example: +Asynchronous rmdir(2). No arguments other than a possible exception are given +to the completion callback. - fs.appendFile('message.txt', 'data to append', function (err) { - if (err) throw err; - console.log('The "data to append" was appended to file!'); - }); +## fs.rmdirSync(path) -If `options` is a string, then it specifies the encoding. Example: +Synchronous rmdir(2). Returns `undefined`. - fs.appendFile('message.txt', 'data to append', 'utf8', callback); +## fs.stat(path, callback) -## fs.appendFileSync(filename, data[, options]) +Asynchronous stat(2). The callback gets two arguments `(err, stats)` where +`stats` is a [fs.Stats](#fs_class_fs_stats) object. See the [fs.Stats](#fs_class_fs_stats) +section below for more information. -The synchronous version of `fs.appendFile`. Returns `undefined`. +## fs.statSync(path) + +Synchronous stat(2). Returns an instance of `fs.Stats`. + +## fs.symlink(destination, path[, type], callback) + +Asynchronous symlink(2). No arguments other than a possible exception are given +to the completion callback. +The `type` argument can be set to `'dir'`, `'file'`, or `'junction'` (default +is `'file'`) and is only available on Windows (ignored on other platforms). +Note that Windows junction points require the destination path to be absolute. When using +`'junction'`, the `destination` argument will automatically be normalized to absolute path. + +## fs.symlinkSync(destination, path[, type]) + +Synchronous symlink(2). Returns `undefined`. + +## fs.truncate(path, len, callback) + +Asynchronous truncate(2). No arguments other than a possible exception are +given to the completion callback. A file descriptor can also be passed as the +first argument. In this case, `fs.ftruncate()` is called. + +## fs.truncateSync(path, len) + +Synchronous truncate(2). Returns `undefined`. + +## fs.unlink(path, callback) + +Asynchronous unlink(2). No arguments other than a possible exception are given +to the completion callback. + +## fs.unlinkSync(path) + +Synchronous unlink(2). Returns `undefined`. + +## fs.unwatchFile(filename[, listener]) + +Stop watching for changes on `filename`. If `listener` is specified, only that +particular listener is removed. Otherwise, *all* listeners are removed and you +have effectively stopped watching `filename`. + +Calling `fs.unwatchFile()` with a filename that is not being watched is a +no-op, not an error. + +_Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`. +`fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` +when possible._ + +## fs.utimes(path, atime, mtime, callback) + +Change file timestamps of the file referenced by the supplied path. + +## fs.utimesSync(path, atime, mtime) + +Synchronous version of `fs.utimes()`. Returns `undefined`. + +## fs.watch(filename[, options][, listener]) + +Watch for changes on `filename`, where `filename` is either a file or a +directory. The returned object is a [fs.FSWatcher](#fs_class_fs_fswatcher). + +The second argument is optional. The `options` if provided should be an object. +The supported boolean members are `persistent` and `recursive`. `persistent` +indicates whether the process should continue to run as long as files are being +watched. `recursive` indicates whether all subdirectories should be watched, or +only the current directory. This applies when a directory is specified, and only +on supported platforms (See Caveats below). + +The default is `{ persistent: true, recursive: false }`. + +The listener callback gets two arguments `(event, filename)`. `event` is either +'rename' or 'change', and `filename` is the name of the file which triggered +the event. + +### Caveats + + + +The `fs.watch` API is not 100% consistent across platforms, and is +unavailable in some situations. + +The recursive option is currently supported on OS X. Only FSEvents supports this +type of file watching so it is unlikely any additional platforms will be added +soon. + +#### Availability + + + +This feature depends on the underlying operating system providing a way +to be notified of filesystem changes. + +* On Linux systems, this uses `inotify`. +* On BSD systems, this uses `kqueue`. +* On OS X, this uses `kqueue` for files and 'FSEvents' for directories. +* On SunOS systems (including Solaris and SmartOS), this uses `event ports`. +* On Windows systems, this feature depends on `ReadDirectoryChangesW`. + +If the underlying functionality is not available for some reason, then +`fs.watch` will not be able to function. For example, watching files or +directories on network file systems (NFS, SMB, etc.) often doesn't work +reliably or at all. + +You can still use `fs.watchFile`, which uses stat polling, but it is slower and +less reliable. + +#### Filename Argument + + + +Providing `filename` argument in the callback is not supported +on every platform (currently it's only supported on Linux and Windows). Even +on supported platforms `filename` is not always guaranteed to be provided. +Therefore, don't assume that `filename` argument is always provided in the +callback, and have some fallback logic if it is null. + + fs.watch('somedir', function (event, filename) { + console.log('event is: ' + event); + if (filename) { + console.log('filename provided: ' + filename); + } else { + console.log('filename not provided'); + } + }); ## fs.watchFile(filename[, options], listener) @@ -587,148 +703,123 @@ _Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible._ -## fs.unwatchFile(filename[, listener]) +## fs.write(fd, buffer, offset, length[, position], callback) -Stop watching for changes on `filename`. If `listener` is specified, only that -particular listener is removed. Otherwise, *all* listeners are removed and you -have effectively stopped watching `filename`. +Write `buffer` to the file specified by `fd`. -Calling `fs.unwatchFile()` with a filename that is not being watched is a -no-op, not an error. +`offset` and `length` determine the part of the buffer to be written. -_Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`. -`fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` -when possible._ +`position` refers to the offset from the beginning of the file where this data +should be written. If `typeof position !== 'number'`, the data will be written +at the current position. See pwrite(2). -## fs.watch(filename[, options][, listener]) +The callback will be given three arguments `(err, written, buffer)` where +`written` specifies how many _bytes_ were written from `buffer`. + +Note that it is unsafe to use `fs.write` multiple times on the same file +without waiting for the callback. For this scenario, +`fs.createWriteStream` is strongly recommended. -Watch for changes on `filename`, where `filename` is either a file or a -directory. The returned object is a [fs.FSWatcher](#fs_class_fs_fswatcher). +On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file. -The second argument is optional. The `options` if provided should be an object. -The supported boolean members are `persistent` and `recursive`. `persistent` -indicates whether the process should continue to run as long as files are being -watched. `recursive` indicates whether all subdirectories should be watched, or -only the current directory. This applies when a directory is specified, and only -on supported platforms (See Caveats below). +## fs.write(fd, data[, position[, encoding]], callback) -The default is `{ persistent: true, recursive: false }`. +Write `data` to the file specified by `fd`. If `data` is not a Buffer instance +then the value will be coerced to a string. -The listener callback gets two arguments `(event, filename)`. `event` is either -'rename' or 'change', and `filename` is the name of the file which triggered -the event. +`position` refers to the offset from the beginning of the file where this data +should be written. If `typeof position !== 'number'` the data will be written at +the current position. See pwrite(2). -### Caveats +`encoding` is the expected string encoding. - +The callback will receive the arguments `(err, written, string)` where `written` +specifies how many _bytes_ the passed string required to be written. Note that +bytes written is not the same as string characters. See +[Buffer.byteLength](buffer.html#buffer_class_method_buffer_bytelength_string_encoding). -The `fs.watch` API is not 100% consistent across platforms, and is -unavailable in some situations. +Unlike when writing `buffer`, the entire string must be written. No substring +may be specified. This is because the byte offset of the resulting data may not +be the same as the string offset. -The recursive option is currently supported on OS X. Only FSEvents supports this -type of file watching so it is unlikely any additional platforms will be added -soon. +Note that it is unsafe to use `fs.write` multiple times on the same file +without waiting for the callback. For this scenario, +`fs.createWriteStream` is strongly recommended. -#### Availability +On Linux, positional writes don't work when the file is opened in append mode. +The kernel ignores the position argument and always appends the data to +the end of the file. - +## fs.writeSync(fd, buffer, offset, length[, position]) -This feature depends on the underlying operating system providing a way -to be notified of filesystem changes. +## fs.writeSync(fd, data[, position[, encoding]]) -* On Linux systems, this uses `inotify`. -* On BSD systems, this uses `kqueue`. -* On OS X, this uses `kqueue` for files and 'FSEvents' for directories. -* On SunOS systems (including Solaris and SmartOS), this uses `event ports`. -* On Windows systems, this feature depends on `ReadDirectoryChangesW`. +Synchronous versions of `fs.write()`. Returns the number of bytes written. -If the underlying functionality is not available for some reason, then -`fs.watch` will not be able to function. For example, watching files or -directories on network file systems (NFS, SMB, etc.) often doesn't work -reliably or at all. +## fs.writeFile(filename, data[, options], callback) -You can still use `fs.watchFile`, which uses stat polling, but it is slower and -less reliable. +* `filename` {String} +* `data` {String | Buffer} +* `options` {Object | String} + * `encoding` {String | Null} default = `'utf8'` + * `mode` {Number} default = `0o666` + * `flag` {String} default = `'w'` +* `callback` {Function} -#### Filename Argument +Asynchronously writes data to a file, replacing the file if it already exists. +`data` can be a string or a buffer. - +The `encoding` option is ignored if `data` is a buffer. It defaults +to `'utf8'`. -Providing `filename` argument in the callback is not supported -on every platform (currently it's only supported on Linux and Windows). Even -on supported platforms `filename` is not always guaranteed to be provided. -Therefore, don't assume that `filename` argument is always provided in the -callback, and have some fallback logic if it is null. +Example: - fs.watch('somedir', function (event, filename) { - console.log('event is: ' + event); - if (filename) { - console.log('filename provided: ' + filename); - } else { - console.log('filename not provided'); - } + fs.writeFile('message.txt', 'Hello io.js', function (err) { + if (err) throw err; + console.log('It\'s saved!'); }); -## fs.exists(path, callback) +If `options` is a string, then it specifies the encoding. Example: -`fs.exists()` is **deprecated**. For supported alternatives please check out -[`fs.stat`](fs.html#fs_fs_stat_path_callback) or -[`fs.access`](fs.html#fs_fs_access_path_mode_callback). + fs.writeFile('message.txt', 'Hello io.js', 'utf8', callback); -Test whether or not the given path exists by checking with the file system. -Then call the `callback` argument with either true or false. Example: +## fs.writeFileSync(filename, data[, options]) - fs.exists('/etc/passwd', function (exists) { - console.log(exists ? "it's there" : 'no passwd!'); - }); +The synchronous version of `fs.writeFile`. Returns `undefined`. -`fs.exists()` is an anachronism and exists only for historical reasons. -There should almost never be a reason to use it in your own code. +## Class: fs.FSWatcher -In particular, checking if a file exists before opening it is an anti-pattern -that leaves you vulnerable to race conditions: another process may remove the -file between the calls to `fs.exists()` and `fs.open()`. Just open the file -and handle the error when it's not there. +Objects returned from `fs.watch()` are of this type. +### watcher.close() +Stop watching for changes on the given `fs.FSWatcher`. -## fs.existsSync(path) +### Event: 'change' -Synchronous version of [`fs.exists`](fs.html#fs_fs_exists_path_callback). -Returns `true` if the file exists, `false` otherwise. +* `event` {String} The type of fs change +* `filename` {String} The filename that changed (if relevant/available) -`fs.existsSync()` is **deprecated**. For supported alternatives please check -out [`fs.statSync`](fs.html#fs_fs_statsync_path) or -[`fs.accessSync`](fs.html#fs_fs_accesssync_path_mode). +Emitted when something changes in a watched directory or file. +See more details in [fs.watch](#fs_fs_watch_filename_options_listener). -## fs.access(path[, mode], callback) +### Event: 'error' -Tests a user's permissions for the file specified by `path`. `mode` is an -optional integer that specifies the accessibility checks to be performed. The -following constants define the possible values of `mode`. It is possible to -create a mask consisting of the bitwise OR of two or more values. +* `error` {Error object} -- `fs.F_OK` - File is visible to the calling process. This is useful for -determining if a file exists, but says nothing about `rwx` permissions. -Default 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 -on Windows (will behave like `fs.F_OK`). +Emitted when an error occurs. -The final argument, `callback`, is a callback function that is invoked with -a possible error argument. If any of the accessibility checks fail, the error -argument will be populated. The following example checks if the file -`/etc/passwd` can be read and written by the current process. +## Class: fs.ReadStream - fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) { - console.log(err ? 'no access!' : 'can read/write'); - }); +`ReadStream` is a [Readable Stream](stream.html#stream_class_stream_readable). -## fs.accessSync(path[, mode]) +### Event: 'open' -Synchronous version of `fs.access`. This throws if any accessibility checks -fail, and does nothing otherwise. +* `fd` {Integer} file descriptor used by the ReadStream. + +Emitted when the ReadStream's file is opened. ## Class: fs.Stats @@ -798,112 +889,17 @@ Prior to io.js v1.0 and Node v0.12, the `ctime` held the `birthtime` on Windows systems. Note that as of v0.12, `ctime` is not "creation time", and on Unix systems, it never was. -## fs.createReadStream(path[, options]) - -Returns a new ReadStream object (See `Readable Stream`). - -Be aware that, unlike the default value set for `highWaterMark` on a -readable stream (16 kb), the stream returned by this method has a -default value of 64 kb for the same parameter. - -`options` is an object or string with the following defaults: - - { flags: 'r', - encoding: null, - fd: null, - mode: 0o666, - autoClose: true - } - -`options` can include `start` and `end` values to read a range of bytes from -the file instead of the entire file. Both `start` and `end` are inclusive and -start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`. - -If `fd` is specified, `ReadStream` will ignore the `path` argument and will use -the specified file descriptor. This means that no `open` event will be emitted. - -If `autoClose` is false, then the file descriptor won't be closed, even if -there's an error. It is your responsibility to close it and make sure -there's no file descriptor leak. If `autoClose` is set to true (default -behavior), on `error` or `end` the file descriptor will be closed -automatically. - -`mode` sets the file mode (permission and sticky bits), but only if the -file was created. - -An example to read the last 10 bytes of a file which is 100 bytes long: - - fs.createReadStream('sample.txt', {start: 90, end: 99}); - -If `options` is a string, then it specifies the encoding. - -## Class: fs.ReadStream - -`ReadStream` is a [Readable Stream](stream.html#stream_class_stream_readable). - -### Event: 'open' - -* `fd` {Integer} file descriptor used by the ReadStream. - -Emitted when the ReadStream's file is opened. - - -## fs.createWriteStream(path[, options]) - -Returns a new WriteStream object (See `Writable Stream`). - -`options` is an object or string with the following defaults: - - { flags: 'w', - defaultEncoding: 'utf8', - fd: null, - mode: 0o666 } - -`options` may also include a `start` option to allow writing data at -some position past the beginning of the file. Modifying a file rather -than replacing it may require a `flags` mode of `r+` rather than the -default mode `w`. The `defaultEncoding` can be `'utf8'`, `'ascii'`, `binary`, -or `'base64'`. - -Like `ReadStream` above, if `fd` is specified, `WriteStream` will ignore the -`path` argument and will use the specified file descriptor. This means that no -`open` event will be emitted. - -If `options` is a string, then it specifies the encoding. - ## Class: fs.WriteStream `WriteStream` is a [Writable Stream](stream.html#stream_class_stream_writable). -### Event: 'open' - -* `fd` {Integer} file descriptor used by the WriteStream. - -Emitted when the WriteStream's file is opened. - ### file.bytesWritten The number of bytes written so far. Does not include data that is still queued for writing. -## Class: fs.FSWatcher - -Objects returned from `fs.watch()` are of this type. - -### watcher.close() - -Stop watching for changes on the given `fs.FSWatcher`. - -### Event: 'change' - -* `event` {String} The type of fs change -* `filename` {String} The filename that changed (if relevant/available) - -Emitted when something changes in a watched directory or file. -See more details in [fs.watch](#fs_fs_watch_filename_options_listener). - -### Event: 'error' +### Event: 'open' -* `error` {Error object} +* `fd` {Integer} file descriptor used by the WriteStream. -Emitted when an error occurs. +Emitted when the WriteStream's file is opened.