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 relative
65 ## fs.rename(path1, path2, [callback])
67 Asynchronous rename(2). No arguments other than a possible exception are given
68 to the completion callback.
70 ## fs.renameSync(path1, path2)
72 Synchronous rename(2).
74 ## fs.truncate(fd, len, [callback])
76 Asynchronous ftruncate(2). No arguments other than a possible exception are
77 given to the completion callback.
79 ## fs.truncateSync(fd, len)
81 Synchronous ftruncate(2).
83 ## fs.chown(path, uid, gid, [callback])
85 Asynchronous chown(2). No arguments other than a possible exception are given
86 to the completion callback.
88 ## fs.chownSync(path, uid, gid)
92 ## fs.fchown(fd, uid, gid, [callback])
94 Asynchronous fchown(2). No arguments other than a possible exception are given
95 to the completion callback.
97 ## fs.fchownSync(fd, uid, gid)
99 Synchronous fchown(2).
101 ## fs.lchown(path, uid, gid, [callback])
103 Asynchronous lchown(2). No arguments other than a possible exception are given
104 to the completion callback.
106 ## fs.lchownSync(path, uid, gid)
108 Synchronous lchown(2).
110 ## fs.chmod(path, mode, [callback])
112 Asynchronous chmod(2). No arguments other than a possible exception are given
113 to the completion callback.
115 ## fs.chmodSync(path, mode)
117 Synchronous chmod(2).
119 ## fs.fchmod(fd, mode, [callback])
121 Asynchronous fchmod(2). No arguments other than a possible exception
122 are given to the completion callback.
124 ## fs.fchmodSync(fd, mode)
126 Synchronous fchmod(2).
128 ## fs.lchmod(path, mode, [callback])
130 Asynchronous lchmod(2). No arguments other than a possible exception
131 are given to the completion callback.
133 ## fs.lchmodSync(path, mode)
135 Synchronous lchmod(2).
137 ## fs.stat(path, [callback])
139 Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
140 `stats` is a [fs.Stats](#fs_class_fs_stats) object. See the [fs.Stats](#fs_class_fs_stats)
141 section below for more information.
143 ## fs.lstat(path, [callback])
145 Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where
146 `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if
147 `path` is a symbolic link, then the link itself is stat-ed, not the file that it
150 ## fs.fstat(fd, [callback])
152 Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
153 `stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that
154 the file to be stat-ed is specified by the file descriptor `fd`.
158 Synchronous stat(2). Returns an instance of `fs.Stats`.
160 ## fs.lstatSync(path)
162 Synchronous lstat(2). Returns an instance of `fs.Stats`.
166 Synchronous fstat(2). Returns an instance of `fs.Stats`.
168 ## fs.link(srcpath, dstpath, [callback])
170 Asynchronous link(2). No arguments other than a possible exception are given to
171 the completion callback.
173 ## fs.linkSync(srcpath, dstpath)
177 ## fs.symlink(linkdata, path, [type], [callback])
179 Asynchronous symlink(2). No arguments other than a possible exception are given
180 to the completion callback.
181 `type` argument can be either `'dir'` or `'file'` (default is `'file'`). It is only
182 used on Windows (ignored on other platforms).
184 ## fs.symlinkSync(linkdata, path, [type])
186 Synchronous symlink(2).
188 ## fs.readlink(path, [callback])
190 Asynchronous readlink(2). The callback gets two arguments `(err,
193 ## fs.readlinkSync(path)
195 Synchronous readlink(2). Returns the symbolic link's string value.
197 ## fs.realpath(path, [callback])
199 Asynchronous realpath(2). The callback gets two arguments `(err,
200 resolvedPath)`. May use `process.cwd` to resolve relative paths.
202 ## fs.realpathSync(path)
204 Synchronous realpath(2). Returns the resolved path.
206 ## fs.unlink(path, [callback])
208 Asynchronous unlink(2). No arguments other than a possible exception are given
209 to the completion callback.
211 ## fs.unlinkSync(path)
213 Synchronous unlink(2).
215 ## fs.rmdir(path, [callback])
217 Asynchronous rmdir(2). No arguments other than a possible exception are given
218 to the completion callback.
220 ## fs.rmdirSync(path)
222 Synchronous rmdir(2).
224 ## fs.mkdir(path, [mode], [callback])
226 Asynchronous mkdir(2). No arguments other than a possible exception are given
227 to the completion callback. `mode` defaults to `0777`.
229 ## fs.mkdirSync(path, [mode])
231 Synchronous mkdir(2).
233 ## fs.readdir(path, [callback])
235 Asynchronous readdir(3). Reads the contents of a directory.
236 The callback gets two arguments `(err, files)` where `files` is an array of
237 the names of the files in the directory excluding `'.'` and `'..'`.
239 ## fs.readdirSync(path)
241 Synchronous readdir(3). Returns an array of filenames excluding `'.'` and
244 ## fs.close(fd, [callback])
246 Asynchronous close(2). No arguments other than a possible exception are given
247 to the completion callback.
251 Synchronous close(2).
253 ## fs.open(path, flags, [mode], [callback])
255 Asynchronous file open. See open(2). `flags` can be:
257 * `'r'` - Open file for reading.
258 An exception occurs if the file does not exist.
260 * `'r+'` - Open file for reading and writing.
261 An exception occurs if the file does not exist.
263 * `'w'` - Open file for writing.
264 The file is created (if it does not exist) or truncated (if it exists).
266 * `'wx'` - Like `'w'` but opens the file in exclusive mode.
268 * `'w+'` - Open file for reading and writing.
269 The file is created (if it does not exist) or truncated (if it exists).
271 * `'wx+'` - Like `'w+'` but opens the file in exclusive mode.
273 * `'a'` - Open file for appending.
274 The file is created if it does not exist.
276 * `'ax'` - Like `'a'` but opens the file in exclusive mode.
278 * `'a+'` - Open file for reading and appending.
279 The file is created if it does not exist.
281 * `'ax+'` - Like `'a+'` but opens the file in exclusive mode.
283 `mode` defaults to `0666`. The callback gets two arguments `(err, fd)`.
285 Exclusive mode (`O_EXCL`) ensures that `path` is newly created. `fs.open()`
286 fails if a file by that name already exists. On POSIX systems, symlinks are
287 not followed. Exclusive mode may or may not work with network file systems.
289 ## fs.openSync(path, flags, [mode])
293 ## fs.utimes(path, atime, mtime, [callback])
294 ## fs.utimesSync(path, atime, mtime)
296 Change file timestamps of the file referenced by the supplied path.
298 ## fs.futimes(fd, atime, mtime, [callback])
299 ## fs.futimesSync(fd, atime, mtime)
301 Change the file timestamps of a file referenced by the supplied file
304 ## fs.fsync(fd, [callback])
306 Asynchronous fsync(2). No arguments other than a possible exception are given
307 to the completion callback.
311 Synchronous fsync(2).
313 ## fs.write(fd, buffer, offset, length, position, [callback])
315 Write `buffer` to the file specified by `fd`.
317 `offset` and `length` determine the part of the buffer to be written.
319 `position` refers to the offset from the beginning of the file where this data
320 should be written. If `position` is `null`, the data will be written at the
324 The callback will be given three arguments `(err, written, buffer)` where `written`
325 specifies how many _bytes_ were written from `buffer`.
327 Note that it is unsafe to use `fs.write` multiple times on the same file
328 without waiting for the callback. For this scenario,
329 `fs.createWriteStream` is strongly recommended.
331 ## fs.writeSync(fd, buffer, offset, length, position)
333 Synchronous version of buffer-based `fs.write()`. Returns the number of bytes
336 ## fs.writeSync(fd, str, position, [encoding])
338 Synchronous version of string-based `fs.write()`. `encoding` defaults to
339 `'utf8'`. Returns the number of _bytes_ written.
341 ## fs.read(fd, buffer, offset, length, position, [callback])
343 Read data from the file specified by `fd`.
345 `buffer` is the buffer that the data will be written to.
347 `offset` is offset within the buffer where writing will start.
349 `length` is an integer specifying the number of bytes to read.
351 `position` is an integer specifying where to begin reading from in the file.
352 If `position` is `null`, data will be read from the current file position.
354 The callback is given the three arguments, `(err, bytesRead, buffer)`.
356 ## fs.readSync(fd, buffer, offset, length, position)
358 Synchronous version of buffer-based `fs.read`. Returns the number of
361 ## fs.readSync(fd, length, position, encoding)
363 Synchronous version of string-based `fs.read`. Returns the number of
366 ## fs.readFile(filename, [encoding], [callback])
368 Asynchronously reads the entire contents of a file. Example:
370 fs.readFile('/etc/passwd', function (err, data) {
375 The callback is passed two arguments `(err, data)`, where `data` is the
376 contents of the file.
378 If no encoding is specified, then the raw buffer is returned.
381 ## fs.readFileSync(filename, [encoding])
383 Synchronous version of `fs.readFile`. Returns the contents of the `filename`.
385 If `encoding` is specified then this function returns a string. Otherwise it
389 ## fs.writeFile(filename, data, [encoding], [callback])
391 Asynchronously writes data to a file, replacing the file if it already exists.
392 `data` can be a string or a buffer. The `encoding` argument is ignored if
393 `data` is a buffer. It defaults to `'utf8'`.
397 fs.writeFile('message.txt', 'Hello Node', function (err) {
399 console.log('It\'s saved!');
402 ## fs.writeFileSync(filename, data, [encoding])
404 The synchronous version of `fs.writeFile`.
406 ## fs.appendFile(filename, data, encoding='utf8', [callback])
408 Asynchronously append data to a file, creating the file if it not yet exists.
409 `data` can be a string or a buffer. The `encoding` argument is ignored if
414 fs.appendFile('message.txt', 'data to append', function (err) {
416 console.log('The "data to append" was appended to file!');
419 ## fs.appendFileSync(filename, data, encoding='utf8')
421 The synchronous version of `fs.appendFile`.
423 ## fs.watchFile(filename, [options], listener)
425 Stability: 2 - Unstable. Use fs.watch instead, if available.
427 Watch for changes on `filename`. The callback `listener` will be called each
428 time the file is accessed.
430 The second argument is optional. The `options` if provided should be an object
431 containing two members a boolean, `persistent`, and `interval`. `persistent`
432 indicates whether the process should continue to run as long as files are
433 being watched. `interval` indicates how often the target should be polled,
434 in milliseconds. (On Linux systems with inotify, `interval` is ignored.) The
435 default is `{ persistent: true, interval: 0 }`.
437 The `listener` gets two arguments the current stat object and the previous
440 fs.watchFile('message.text', function (curr, prev) {
441 console.log('the current mtime is: ' + curr.mtime);
442 console.log('the previous mtime was: ' + prev.mtime);
445 These stat objects are instances of `fs.Stat`.
447 If you want to be notified when the file was modified, not just accessed
448 you need to compare `curr.mtime` and `prev.mtime`.
451 ## fs.unwatchFile(filename)
453 Stability: 2 - Unstable. Use fs.watch instead, if available.
455 Stop watching for changes on `filename`.
457 ## fs.watch(filename, [options], listener)
459 Stability: 2 - Unstable. Not available on all platforms.
461 Watch for changes on `filename`, where `filename` is either a file or a
462 directory. The returned object is a [fs.FSWatcher](#fs_class_fs_fswatcher).
464 The second argument is optional. The `options` if provided should be an object
465 containing a boolean member `persistent`, which indicates whether the process
466 should continue to run as long as files are being watched. The default is
467 `{ persistent: true }`.
469 The listener callback gets two arguments `(event, filename)`. `event` is either
470 'rename' or 'change', and `filename` is the name of the file which triggered
477 The `fs.watch` API is not 100% consistent across platforms, and is
478 unavailable in some situations.
484 This feature depends on the underlying operating system providing a way
485 to be notified of filesystem changes.
487 * On Linux systems, this uses `inotify`.
488 * On BSD systems (including OS X), this uses `kqueue`.
489 * On SunOS systems (including Solaris and SmartOS), this uses `event ports`.
490 * On Windows systems, this feature depends on `ReadDirectoryChangesW`.
492 If the underlying functionality is not available for some reason, then
493 `fs.watch` will not be able to function. You can still use
494 `fs.watchFile`, which uses stat polling, but it is slower and less
497 #### Filename Argument
501 Providing `filename` argument in the callback is not supported
502 on every platform (currently it's only supported on Linux and Windows). Even
503 on supported platforms `filename` is not always guaranteed to be provided.
504 Therefore, don't assume that `filename` argument is always provided in the
505 callback, and have some fallback logic if it is null.
507 fs.watch('somedir', function (event, filename) {
508 console.log('event is: ' + event);
510 console.log('filename provided: ' + filename);
512 console.log('filename not provided');
516 ## fs.exists(p, [callback])
518 Test whether or not the given path exists by checking with the file system.
519 Then call the `callback` argument with either true or false. Example:
521 fs.exists('/etc/passwd', function (exists) {
522 util.debug(exists ? "it's there" : "no passwd!");
528 Synchronous version of `fs.exists`.
532 Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their
533 synchronous counterparts are of this type.
536 - `stats.isDirectory()`
537 - `stats.isBlockDevice()`
538 - `stats.isCharacterDevice()`
539 - `stats.isSymbolicLink()` (only valid with `fs.lstat()`)
543 For a regular file `util.inspect(stats)` would return a string very
556 atime: Mon, 10 Oct 2011 23:24:11 GMT,
557 mtime: Mon, 10 Oct 2011 23:24:11 GMT,
558 ctime: Mon, 10 Oct 2011 23:24:11 GMT }
560 Please note that `atime`, `mtime` and `ctime` are instances
561 of [Date][MDN-Date] object and to compare the values of
562 these objects you should use appropriate methods. For most
563 general uses [getTime()][MDN-Date-getTime] will return
564 the number of milliseconds elapsed since _1 January 1970
565 00:00:00 UTC_ and this integer should be sufficient for
566 any comparison, however there additional methods which can
567 be used for displaying fuzzy information. More details can
568 be found in the [MDN JavaScript Reference][MDN-Date] page.
570 [MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
571 [MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
574 ## fs.createReadStream(path, [options])
576 Returns a new ReadStream object (See `Readable Stream`).
578 `options` is an object with the following defaults:
584 bufferSize: 64 * 1024
587 `options` can include `start` and `end` values to read a range of bytes from
588 the file instead of the entire file. Both `start` and `end` are inclusive and
589 start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`.
591 An example to read the last 10 bytes of a file which is 100 bytes long:
593 fs.createReadStream('sample.txt', {start: 90, end: 99});
596 ## Class: fs.ReadStream
598 `ReadStream` is a [Readable Stream](stream.html#stream_readable_stream).
602 * `fd` {Integer} file descriptor used by the ReadStream.
604 Emitted when the ReadStream's file is opened.
607 ## fs.createWriteStream(path, [options])
609 Returns a new WriteStream object (See `Writable Stream`).
611 `options` is an object with the following defaults:
617 `options` may also include a `start` option to allow writing data at
618 some position past the beginning of the file. Modifying a file rather
619 than replacing it may require a `flags` mode of `r+` rather than the
624 `WriteStream` is a [Writable Stream](stream.html#stream_writable_stream).
628 * `fd` {Integer} file descriptor used by the WriteStream.
630 Emitted when the WriteStream's file is opened.
632 ### file.bytesWritten
634 The number of bytes written so far. Does not include data that is still queued
637 ## Class: fs.FSWatcher
639 Objects returned from `fs.watch()` are of this type.
643 Stop watching for changes on the given `fs.FSWatcher`.
647 * `event` {String} The type of fs change
648 * `filename` {String} The filename that changed (if relevant/available)
650 Emitted when something changes in a watched directory or file.
651 See more details in [fs.watch](#fs_fs_watch_filename_options_listener).
655 * `error` {Error object}
657 Emitted when an error occurs.