7 File I/O is provided by simple wrappers around standard POSIX functions. To
8 use this module do `require('fs')`. All the methods have asynchronous and
11 The asynchronous form always take a completion callback as its last argument.
12 The arguments passed to the completion callback depend on the method, but the
13 first argument is always reserved for an exception. If the operation was
14 completed successfully, then the first argument will be `null` or `undefined`.
16 When using the synchronous form any exceptions are immediately thrown.
17 You can use try/catch to handle exceptions or allow them to bubble up.
19 Here is an example of the asynchronous version:
21 var fs = require('fs');
23 fs.unlink('/tmp/hello', function (err) {
25 console.log('successfully deleted /tmp/hello');
28 Here is the synchronous version:
30 var fs = require('fs');
32 fs.unlinkSync('/tmp/hello')
33 console.log('successfully deleted /tmp/hello');
35 With the asynchronous methods there is no guaranteed ordering. So the
36 following is prone to error:
38 fs.rename('/tmp/hello', '/tmp/world', function (err) {
40 console.log('renamed complete');
42 fs.stat('/tmp/world', function (err, stats) {
44 console.log('stats: ' + JSON.stringify(stats));
47 It could be that `fs.stat` is executed before `fs.rename`.
48 The correct way to do this is to chain the callbacks.
50 fs.rename('/tmp/hello', '/tmp/world', function (err) {
52 fs.stat('/tmp/world', function (err, stats) {
54 console.log('stats: ' + JSON.stringify(stats));
58 In busy processes, the programmer is _strongly encouraged_ to use the
59 asynchronous versions of these calls. The synchronous versions will block
60 the entire process until they complete--halting all connections.
62 Relative path to filename can be used, remember however that this path will be
63 relative to `process.cwd()`.
65 Most fs functions let you omit the callback argument. If you do, a default
66 callback is used that rethrows errors. To get a trace to the original call
67 site, set the NODE_DEBUG environment variable:
71 require('fs').readFile('/');
75 $ env NODE_DEBUG=fs node script.js
80 at rethrow (fs.js:61:21)
81 at maybeCallback (fs.js:79:42)
82 at Object.fs.readFile (fs.js:153:18)
83 at bad (/path/to/script.js:2:17)
84 at Object.<anonymous> (/path/to/script.js:5:1)
88 ## fs.rename(oldPath, newPath, callback)
90 Asynchronous rename(2). No arguments other than a possible exception are given
91 to the completion callback.
93 ## fs.renameSync(oldPath, newPath)
95 Synchronous rename(2).
97 ## fs.ftruncate(fd, len, callback)
99 Asynchronous ftruncate(2). No arguments other than a possible exception are
100 given to the completion callback.
102 ## fs.ftruncateSync(fd, len)
104 Synchronous ftruncate(2).
106 ## fs.truncate(path, len, callback)
108 Asynchronous truncate(2). No arguments other than a possible exception are
109 given to the completion callback.
111 ## fs.truncateSync(path, len)
113 Synchronous truncate(2).
115 ## fs.chown(path, uid, gid, callback)
117 Asynchronous chown(2). No arguments other than a possible exception are given
118 to the completion callback.
120 ## fs.chownSync(path, uid, gid)
122 Synchronous chown(2).
124 ## fs.fchown(fd, uid, gid, callback)
126 Asynchronous fchown(2). No arguments other than a possible exception are given
127 to the completion callback.
129 ## fs.fchownSync(fd, uid, gid)
131 Synchronous fchown(2).
133 ## fs.lchown(path, uid, gid, callback)
135 Asynchronous lchown(2). No arguments other than a possible exception are given
136 to the completion callback.
138 ## fs.lchownSync(path, uid, gid)
140 Synchronous lchown(2).
142 ## fs.chmod(path, mode, callback)
144 Asynchronous chmod(2). No arguments other than a possible exception are given
145 to the completion callback.
147 ## fs.chmodSync(path, mode)
149 Synchronous chmod(2).
151 ## fs.fchmod(fd, mode, callback)
153 Asynchronous fchmod(2). No arguments other than a possible exception
154 are given to the completion callback.
156 ## fs.fchmodSync(fd, mode)
158 Synchronous fchmod(2).
160 ## fs.lchmod(path, mode, callback)
162 Asynchronous lchmod(2). No arguments other than a possible exception
163 are given to the completion callback.
165 Only available on Mac OS X.
167 ## fs.lchmodSync(path, mode)
169 Synchronous lchmod(2).
171 ## fs.stat(path, callback)
173 Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
174 `stats` is a [fs.Stats](#fs_class_fs_stats) object. See the [fs.Stats](#fs_class_fs_stats)
175 section below for more information.
177 ## fs.lstat(path, callback)
179 Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where
180 `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if
181 `path` is a symbolic link, then the link itself is stat-ed, not the file that it
184 ## fs.fstat(fd, callback)
186 Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
187 `stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that
188 the file to be stat-ed is specified by the file descriptor `fd`.
192 Synchronous stat(2). Returns an instance of `fs.Stats`.
194 ## fs.lstatSync(path)
196 Synchronous lstat(2). Returns an instance of `fs.Stats`.
200 Synchronous fstat(2). Returns an instance of `fs.Stats`.
202 ## fs.link(srcpath, dstpath, callback)
204 Asynchronous link(2). No arguments other than a possible exception are given to
205 the completion callback.
207 ## fs.linkSync(srcpath, dstpath)
211 ## fs.symlink(srcpath, dstpath, [type], callback)
213 Asynchronous symlink(2). No arguments other than a possible exception are given
214 to the completion callback.
215 `type` argument can be either `'dir'`, `'file'`, or `'junction'` (default is `'file'`). It is only
216 used on Windows (ignored on other platforms).
217 Note that Windows junction points require the destination path to be absolute. When using
218 `'junction'`, the `destination` argument will automatically be normalized to absolute path.
220 ## fs.symlinkSync(srcpath, dstpath, [type])
222 Synchronous symlink(2).
224 ## fs.readlink(path, callback)
226 Asynchronous readlink(2). The callback gets two arguments `(err,
229 ## fs.readlinkSync(path)
231 Synchronous readlink(2). Returns the symbolic link's string value.
233 ## fs.realpath(path, [cache], callback)
235 Asynchronous realpath(2). The `callback` gets two arguments `(err,
236 resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an
237 object literal of mapped paths that can be used to force a specific path
238 resolution or avoid additional `fs.stat` calls for known real paths.
242 var cache = {'/etc':'/private/etc'};
243 fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
245 console.log(resolvedPath);
248 ## fs.realpathSync(path, [cache])
250 Synchronous realpath(2). Returns the resolved path.
252 ## fs.unlink(path, callback)
254 Asynchronous unlink(2). No arguments other than a possible exception are given
255 to the completion callback.
257 ## fs.unlinkSync(path)
259 Synchronous unlink(2).
261 ## fs.rmdir(path, callback)
263 Asynchronous rmdir(2). No arguments other than a possible exception are given
264 to the completion callback.
266 ## fs.rmdirSync(path)
268 Synchronous rmdir(2).
270 ## fs.mkdir(path, [mode], callback)
272 Asynchronous mkdir(2). No arguments other than a possible exception are given
273 to the completion callback. `mode` defaults to `0777`.
275 ## fs.mkdirSync(path, [mode])
277 Synchronous mkdir(2).
279 ## fs.readdir(path, callback)
281 Asynchronous readdir(3). Reads the contents of a directory.
282 The callback gets two arguments `(err, files)` where `files` is an array of
283 the names of the files in the directory excluding `'.'` and `'..'`.
285 ## fs.readdirSync(path)
287 Synchronous readdir(3). Returns an array of filenames excluding `'.'` and
290 ## fs.close(fd, callback)
292 Asynchronous close(2). No arguments other than a possible exception are given
293 to the completion callback.
297 Synchronous close(2).
299 ## fs.open(path, flags, [mode], callback)
301 Asynchronous file open. See open(2). `flags` can be:
303 * `'r'` - Open file for reading.
304 An exception occurs if the file does not exist.
306 * `'r+'` - Open file for reading and writing.
307 An exception occurs if the file does not exist.
309 * `'rs'` - Open file for reading in synchronous mode. Instructs the operating
310 system to bypass the local file system cache.
312 This is primarily useful for opening files on NFS mounts as it allows you to
313 skip the potentially stale local cache. It has a very real impact on I/O
314 performance so don't use this mode unless you need it.
316 Note that this doesn't turn `fs.open()` into a synchronous blocking call.
317 If that's what you want then you should be using `fs.openSync()`
319 * `'rs+'` - Open file for reading and writing, telling the OS to open it
320 synchronously. See notes for `'rs'` about using this with caution.
322 * `'w'` - Open file for writing.
323 The file is created (if it does not exist) or truncated (if it exists).
325 * `'wx'` - Like `'w'` but opens the file in exclusive mode.
327 * `'w+'` - Open file for reading and writing.
328 The file is created (if it does not exist) or truncated (if it exists).
330 * `'wx+'` - Like `'w+'` but opens the file in exclusive mode.
332 * `'a'` - Open file for appending.
333 The file is created if it does not exist.
335 * `'ax'` - Like `'a'` but opens the file in exclusive mode.
337 * `'a+'` - Open file for reading and appending.
338 The file is created if it does not exist.
340 * `'ax+'` - Like `'a+'` but opens the file in exclusive mode.
342 `mode` defaults to `0666`. The callback gets two arguments `(err, fd)`.
344 Exclusive mode (`O_EXCL`) ensures that `path` is newly created. `fs.open()`
345 fails if a file by that name already exists. On POSIX systems, symlinks are
346 not followed. Exclusive mode may or may not work with network file systems.
348 ## fs.openSync(path, flags, [mode])
352 ## fs.utimes(path, atime, mtime, callback)
353 ## fs.utimesSync(path, atime, mtime)
355 Change file timestamps of the file referenced by the supplied path.
357 ## fs.futimes(fd, atime, mtime, callback)
358 ## fs.futimesSync(fd, atime, mtime)
360 Change the file timestamps of a file referenced by the supplied file
363 ## fs.fsync(fd, callback)
365 Asynchronous fsync(2). No arguments other than a possible exception are given
366 to the completion callback.
370 Synchronous fsync(2).
372 ## fs.write(fd, buffer, offset, length, position, callback)
374 Write `buffer` to the file specified by `fd`.
376 `offset` and `length` determine the part of the buffer to be written.
378 `position` refers to the offset from the beginning of the file where this data
379 should be written. If `position` is `null`, the data will be written at the
383 The callback will be given three arguments `(err, written, buffer)` where `written`
384 specifies how many _bytes_ were written from `buffer`.
386 Note that it is unsafe to use `fs.write` multiple times on the same file
387 without waiting for the callback. For this scenario,
388 `fs.createWriteStream` is strongly recommended.
390 ## fs.writeSync(fd, buffer, offset, length, position)
392 Synchronous version of `fs.write()`. Returns the number of bytes written.
394 ## fs.read(fd, buffer, offset, length, position, callback)
396 Read data from the file specified by `fd`.
398 `buffer` is the buffer that the data will be written to.
400 `offset` is offset within the buffer where reading will start.
402 `length` is an integer specifying the number of bytes to read.
404 `position` is an integer specifying where to begin reading from in the file.
405 If `position` is `null`, data will be read from the current file position.
407 The callback is given the three arguments, `(err, bytesRead, buffer)`.
409 ## fs.readSync(fd, buffer, offset, length, position)
411 Synchronous version of `fs.read`. Returns the number of `bytesRead`.
413 ## fs.readFile(filename, [options], callback)
415 * `filename` {String}
417 * `encoding` {String | Null} default = `null`
418 * `flag` {String} default = `'r'`
419 * `callback` {Function}
421 Asynchronously reads the entire contents of a file. Example:
423 fs.readFile('/etc/passwd', function (err, data) {
428 The callback is passed two arguments `(err, data)`, where `data` is the
429 contents of the file.
431 If no encoding is specified, then the raw buffer is returned.
434 ## fs.readFileSync(filename, [options])
436 Synchronous version of `fs.readFile`. Returns the contents of the `filename`.
438 If the `encoding` option is specified then this function returns a
439 string. Otherwise it returns a buffer.
442 ## fs.writeFile(filename, data, [options], callback)
444 * `filename` {String}
445 * `data` {String | Buffer}
447 * `encoding` {String | Null} default = `'utf8'`
448 * `mode` {Number} default = `438` (aka `0666` in Octal)
449 * `flag` {String} default = `'w'`
450 * `callback` {Function}
452 Asynchronously writes data to a file, replacing the file if it already exists.
453 `data` can be a string or a buffer.
455 The `encoding` option is ignored if `data` is a buffer. It defaults
460 fs.writeFile('message.txt', 'Hello Node', function (err) {
462 console.log('It\'s saved!');
465 ## fs.writeFileSync(filename, data, [options])
467 The synchronous version of `fs.writeFile`.
469 ## fs.appendFile(filename, data, [options], callback)
471 * `filename` {String}
472 * `data` {String | Buffer}
474 * `encoding` {String | Null} default = `'utf8'`
475 * `mode` {Number} default = `438` (aka `0666` in Octal)
476 * `flag` {String} default = `'a'`
477 * `callback` {Function}
479 Asynchronously append data to a file, creating the file if it not yet exists.
480 `data` can be a string or a buffer.
484 fs.appendFile('message.txt', 'data to append', function (err) {
486 console.log('The "data to append" was appended to file!');
489 ## fs.appendFileSync(filename, data, [options])
491 The synchronous version of `fs.appendFile`.
493 ## fs.watchFile(filename, [options], listener)
495 Stability: 2 - Unstable. Use fs.watch instead, if possible.
497 Watch for changes on `filename`. The callback `listener` will be called each
498 time the file is accessed.
500 The second argument is optional. The `options` if provided should be an object
501 containing two members a boolean, `persistent`, and `interval`. `persistent`
502 indicates whether the process should continue to run as long as files are
503 being watched. `interval` indicates how often the target should be polled,
504 in milliseconds. The default is `{ persistent: true, interval: 5007 }`.
506 The `listener` gets two arguments the current stat object and the previous
509 fs.watchFile('message.text', function (curr, prev) {
510 console.log('the current mtime is: ' + curr.mtime);
511 console.log('the previous mtime was: ' + prev.mtime);
514 These stat objects are instances of `fs.Stat`.
516 If you want to be notified when the file was modified, not just accessed
517 you need to compare `curr.mtime` and `prev.mtime`.
519 ## fs.unwatchFile(filename, [listener])
521 Stability: 2 - Unstable. Use fs.watch instead, if available.
523 Stop watching for changes on `filename`. If `listener` is specified, only that
524 particular listener is removed. Otherwise, *all* listeners are removed and you
525 have effectively stopped watching `filename`.
527 Calling `fs.unwatchFile()` with a filename that is not being watched is a
530 ## fs.watch(filename, [options], [listener])
532 Stability: 2 - Unstable.
534 Watch for changes on `filename`, where `filename` is either a file or a
535 directory. The returned object is a [fs.FSWatcher](#fs_class_fs_fswatcher).
537 The second argument is optional. The `options` if provided should be an object
538 containing a boolean member `persistent`, which indicates whether the process
539 should continue to run as long as files are being watched. The default is
540 `{ persistent: true }`.
542 The listener callback gets two arguments `(event, filename)`. `event` is either
543 'rename' or 'change', and `filename` is the name of the file which triggered
550 The `fs.watch` API is not 100% consistent across platforms, and is
551 unavailable in some situations.
557 This feature depends on the underlying operating system providing a way
558 to be notified of filesystem changes.
560 * On Linux systems, this uses `inotify`.
561 * On BSD systems (including OS X), this uses `kqueue`.
562 * On SunOS systems (including Solaris and SmartOS), this uses `event ports`.
563 * On Windows systems, this feature depends on `ReadDirectoryChangesW`.
565 If the underlying functionality is not available for some reason, then
566 `fs.watch` will not be able to function. For example, watching files or
567 directories on network file systems (NFS, SMB, etc.) often doesn't work
570 You can still use `fs.watchFile`, which uses stat polling, but it is slower and
573 #### Filename Argument
577 Providing `filename` argument in the callback is not supported
578 on every platform (currently it's only supported on Linux and Windows). Even
579 on supported platforms `filename` is not always guaranteed to be provided.
580 Therefore, don't assume that `filename` argument is always provided in the
581 callback, and have some fallback logic if it is null.
583 fs.watch('somedir', function (event, filename) {
584 console.log('event is: ' + event);
586 console.log('filename provided: ' + filename);
588 console.log('filename not provided');
592 ## fs.exists(path, callback)
594 Test whether or not the given path exists by checking with the file system.
595 Then call the `callback` argument with either true or false. Example:
597 fs.exists('/etc/passwd', function (exists) {
598 util.debug(exists ? "it's there" : "no passwd!");
602 ## fs.existsSync(path)
604 Synchronous version of `fs.exists`.
608 Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their
609 synchronous counterparts are of this type.
612 - `stats.isDirectory()`
613 - `stats.isBlockDevice()`
614 - `stats.isCharacterDevice()`
615 - `stats.isSymbolicLink()` (only valid with `fs.lstat()`)
619 For a regular file `util.inspect(stats)` would return a string very
632 atime: Mon, 10 Oct 2011 23:24:11 GMT,
633 mtime: Mon, 10 Oct 2011 23:24:11 GMT,
634 ctime: Mon, 10 Oct 2011 23:24:11 GMT }
636 Please note that `atime`, `mtime` and `ctime` are instances
637 of [Date][MDN-Date] object and to compare the values of
638 these objects you should use appropriate methods. For most
639 general uses [getTime()][MDN-Date-getTime] will return
640 the number of milliseconds elapsed since _1 January 1970
641 00:00:00 UTC_ and this integer should be sufficient for
642 any comparison, however there additional methods which can
643 be used for displaying fuzzy information. More details can
644 be found in the [MDN JavaScript Reference][MDN-Date] page.
646 [MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
647 [MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
650 ## fs.createReadStream(path, [options])
652 Returns a new ReadStream object (See `Readable Stream`).
654 `options` is an object with the following defaults:
660 bufferSize: 64 * 1024,
664 `options` can include `start` and `end` values to read a range of bytes from
665 the file instead of the entire file. Both `start` and `end` are inclusive and
666 start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`.
668 If `autoClose` is false, then the file descriptor won't be closed, even if
669 there's an error. It is your responsiblity to close it and make sure
670 there's no file descriptor leak. If `autoClose` is set to true (default
671 behavior), on `error` or `end` the file descriptor will be closed
674 An example to read the last 10 bytes of a file which is 100 bytes long:
676 fs.createReadStream('sample.txt', {start: 90, end: 99});
679 ## Class: fs.ReadStream
681 `ReadStream` is a [Readable Stream](stream.html#stream_readable_stream).
685 * `fd` {Integer} file descriptor used by the ReadStream.
687 Emitted when the ReadStream's file is opened.
690 ## fs.createWriteStream(path, [options])
692 Returns a new WriteStream object (See `Writable Stream`).
694 `options` is an object with the following defaults:
700 `options` may also include a `start` option to allow writing data at
701 some position past the beginning of the file. Modifying a file rather
702 than replacing it may require a `flags` mode of `r+` rather than the
707 `WriteStream` is a [Writable Stream](stream.html#stream_writable_stream).
711 * `fd` {Integer} file descriptor used by the WriteStream.
713 Emitted when the WriteStream's file is opened.
715 ### file.bytesWritten
717 The number of bytes written so far. Does not include data that is still queued
720 ## Class: fs.FSWatcher
722 Objects returned from `fs.watch()` are of this type.
726 Stop watching for changes on the given `fs.FSWatcher`.
730 * `event` {String} The type of fs change
731 * `filename` {String} The filename that changed (if relevant/available)
733 Emitted when something changes in a watched directory or file.
734 See more details in [fs.watch](#fs_fs_watch_filename_options_listener).
738 * `error` {Error object}
740 Emitted when an error occurs.