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 takes 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 The relative path to a filename can be used. Remember, however, that this path
63 will be 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)
87 ## Class: fs.FSWatcher
89 Objects returned from `fs.watch()` are of this type.
93 * `event` {String} The type of fs change
94 * `filename` {String} The filename that changed (if relevant/available)
96 Emitted when something changes in a watched directory or file.
97 See more details in [fs.watch](#fs_fs_watch_filename_options_listener).
101 * `error` {Error object}
103 Emitted when an error occurs.
107 Stop watching for changes on the given `fs.FSWatcher`.
109 ## Class: fs.ReadStream
111 `ReadStream` is a [Readable Stream](stream.html#stream_class_stream_readable).
115 * `fd` {Integer} file descriptor used by the ReadStream.
117 Emitted when the ReadStream's file is opened.
121 Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their
122 synchronous counterparts are of this type.
125 - `stats.isDirectory()`
126 - `stats.isBlockDevice()`
127 - `stats.isCharacterDevice()`
128 - `stats.isSymbolicLink()` (only valid with `fs.lstat()`)
132 For a regular file `util.inspect(stats)` would return a string very
145 atime: Mon, 10 Oct 2011 23:24:11 GMT,
146 mtime: Mon, 10 Oct 2011 23:24:11 GMT,
147 ctime: Mon, 10 Oct 2011 23:24:11 GMT,
148 birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
150 Please note that `atime`, `mtime`, `birthtime`, and `ctime` are
151 instances of [Date][MDN-Date] object and to compare the values of
152 these objects you should use appropriate methods. For most general
153 uses [getTime()][MDN-Date-getTime] will return the number of
154 milliseconds elapsed since _1 January 1970 00:00:00 UTC_ and this
155 integer should be sufficient for any comparison, however there are
156 additional methods which can be used for displaying fuzzy information.
157 More details can be found in the [MDN JavaScript Reference][MDN-Date]
160 [MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
161 [MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
165 The times in the stat object have the following semantics:
167 * `atime` "Access Time" - Time when file data last accessed. Changed
168 by the `mknod(2)`, `utimes(2)`, and `read(2)` system calls.
169 * `mtime` "Modified Time" - Time when file data last modified.
170 Changed by the `mknod(2)`, `utimes(2)`, and `write(2)` system calls.
171 * `ctime` "Change Time" - Time when file status was last changed
172 (inode data modification). Changed by the `chmod(2)`, `chown(2)`,
173 `link(2)`, `mknod(2)`, `rename(2)`, `unlink(2)`, `utimes(2)`,
174 `read(2)`, and `write(2)` system calls.
175 * `birthtime` "Birth Time" - Time of file creation. Set once when the
176 file is created. On filesystems where birthtime is not available,
177 this field may instead hold either the `ctime` or
178 `1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). On Darwin and
179 other FreeBSD variants, also set if the `atime` is explicitly set to
180 an earlier value than the current `birthtime` using the `utimes(2)`
183 Prior to Node v0.12, the `ctime` held the `birthtime` on Windows
184 systems. Note that as of v0.12, `ctime` is not "creation time", and
185 on Unix systems, it never was.
187 ## Class: fs.WriteStream
189 `WriteStream` is a [Writable Stream](stream.html#stream_class_stream_writable).
193 * `fd` {Integer} file descriptor used by the WriteStream.
195 Emitted when the WriteStream's file is opened.
197 ### writeStream.bytesWritten
199 The number of bytes written so far. Does not include data that is still queued
202 ## fs.access(path[, mode], callback)
204 Tests a user's permissions for the file specified by `path`. `mode` is an
205 optional integer that specifies the accessibility checks to be performed. The
206 following constants define the possible values of `mode`. It is possible to
207 create a mask consisting of the bitwise OR of two or more values.
209 - `fs.F_OK` - File is visible to the calling process. This is useful for
210 determining if a file exists, but says nothing about `rwx` permissions.
211 Default if no `mode` is specified.
212 - `fs.R_OK` - File can be read by the calling process.
213 - `fs.W_OK` - File can be written by the calling process.
214 - `fs.X_OK` - File can be executed by the calling process. This has no effect
215 on Windows (will behave like `fs.F_OK`).
217 The final argument, `callback`, is a callback function that is invoked with
218 a possible error argument. If any of the accessibility checks fail, the error
219 argument will be populated. The following example checks if the file
220 `/etc/passwd` can be read and written by the current process.
222 fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) {
223 console.log(err ? 'no access!' : 'can read/write');
226 ## fs.accessSync(path[, mode])
228 Synchronous version of `fs.access`. This throws if any accessibility checks
229 fail, and does nothing otherwise.
231 ## fs.appendFile(file, data[, options], callback)
233 * `file` {String | Integer} filename or file descriptor
234 * `data` {String | Buffer}
235 * `options` {Object | String}
236 * `encoding` {String | Null} default = `'utf8'`
237 * `mode` {Number} default = `0o666`
238 * `flag` {String} default = `'a'`
239 * `callback` {Function}
241 Asynchronously append data to a file, creating the file if it does not yet exist.
242 `data` can be a string or a buffer.
246 fs.appendFile('message.txt', 'data to append', function (err) {
248 console.log('The "data to append" was appended to file!');
251 If `options` is a string, then it specifies the encoding. Example:
253 fs.appendFile('message.txt', 'data to append', 'utf8', callback);
255 Any specified file descriptor has to have been opened for appending.
257 _Note: Specified file descriptors will not be closed automatically._
259 ## fs.appendFileSync(file, data[, options])
261 The synchronous version of `fs.appendFile`. Returns `undefined`.
263 ## fs.chmod(path, mode, callback)
265 Asynchronous chmod(2). No arguments other than a possible exception are given
266 to the completion callback.
268 ## fs.chmodSync(path, mode)
270 Synchronous chmod(2). Returns `undefined`.
272 ## fs.chown(path, uid, gid, callback)
274 Asynchronous chown(2). No arguments other than a possible exception are given
275 to the completion callback.
277 ## fs.chownSync(path, uid, gid)
279 Synchronous chown(2). Returns `undefined`.
281 ## fs.close(fd, callback)
283 Asynchronous close(2). No arguments other than a possible exception are given
284 to the completion callback.
288 Synchronous close(2). Returns `undefined`.
290 ## fs.createReadStream(path[, options])
292 Returns a new ReadStream object (See `Readable Stream`).
294 Be aware that, unlike the default value set for `highWaterMark` on a
295 readable stream (16 kb), the stream returned by this method has a
296 default value of 64 kb for the same parameter.
298 `options` is an object or string with the following defaults:
307 `options` can include `start` and `end` values to read a range of bytes from
308 the file instead of the entire file. Both `start` and `end` are inclusive and
309 start at 0. The `encoding` can be any one of those accepted by [Buffer][].
311 If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
312 the specified file descriptor. This means that no `open` event will be emitted.
314 If `autoClose` is false, then the file descriptor won't be closed, even if
315 there's an error. It is your responsibility to close it and make sure
316 there's no file descriptor leak. If `autoClose` is set to true (default
317 behavior), on `error` or `end` the file descriptor will be closed
320 `mode` sets the file mode (permission and sticky bits), but only if the
323 An example to read the last 10 bytes of a file which is 100 bytes long:
325 fs.createReadStream('sample.txt', {start: 90, end: 99});
327 If `options` is a string, then it specifies the encoding.
329 ## fs.createWriteStream(path[, options])
331 Returns a new WriteStream object (See `Writable Stream`).
333 `options` is an object or string with the following defaults:
336 defaultEncoding: 'utf8',
340 `options` may also include a `start` option to allow writing data at
341 some position past the beginning of the file. Modifying a file rather
342 than replacing it may require a `flags` mode of `r+` rather than the
343 default mode `w`. The `defaultEncoding` can be any one of those accepted by [Buffer][].
345 Like `ReadStream` above, if `fd` is specified, `WriteStream` will ignore the
346 `path` argument and will use the specified file descriptor. This means that no
347 `open` event will be emitted.
349 If `options` is a string, then it specifies the encoding.
351 ## fs.exists(path, callback)
353 Stability: 0 - Deprecated: Use [fs.stat][] or [fs.access][] instead.
355 Test whether or not the given path exists by checking with the file system.
356 Then call the `callback` argument with either true or false. Example:
358 fs.exists('/etc/passwd', function (exists) {
359 console.log(exists ? "it's there" : 'no passwd!');
362 `fs.exists()` should not be used to check if a file exists before calling
363 `fs.open()`. Doing so introduces a race condition since other processes may
364 change the file's state between the two calls. Instead, user code should
365 call `fs.open()` directly and handle the error raised if the file is
368 ## fs.existsSync(path)
370 Synchronous version of [`fs.exists`](fs.html#fs_fs_exists_path_callback).
371 Returns `true` if the file exists, `false` otherwise.
373 Stability: 0 - Deprecated: Use [fs.statSync][] or [fs.accessSync][] instead.
375 ## fs.fchmod(fd, mode, callback)
377 Asynchronous fchmod(2). No arguments other than a possible exception
378 are given to the completion callback.
380 ## fs.fchmodSync(fd, mode)
382 Synchronous fchmod(2). Returns `undefined`.
384 ## fs.fchown(fd, uid, gid, callback)
386 Asynchronous fchown(2). No arguments other than a possible exception are given
387 to the completion callback.
389 ## fs.fchownSync(fd, uid, gid)
391 Synchronous fchown(2). Returns `undefined`.
393 ## fs.fstat(fd, callback)
395 Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
396 `stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that
397 the file to be stat-ed is specified by the file descriptor `fd`.
401 Synchronous fstat(2). Returns an instance of `fs.Stats`.
403 ## fs.fsync(fd, callback)
405 Asynchronous fsync(2). No arguments other than a possible exception are given
406 to the completion callback.
410 Synchronous fsync(2). Returns `undefined`.
412 ## fs.ftruncate(fd, len, callback)
414 Asynchronous ftruncate(2). No arguments other than a possible exception are
415 given to the completion callback.
417 ## fs.ftruncateSync(fd, len)
419 Synchronous ftruncate(2). Returns `undefined`.
421 ## fs.futimes(fd, atime, mtime, callback)
423 Change the file timestamps of a file referenced by the supplied file
426 ## fs.futimesSync(fd, atime, mtime)
428 Synchronous version of `fs.futimes()`. Returns `undefined`.
430 ## fs.lchmod(path, mode, callback)
432 Asynchronous lchmod(2). No arguments other than a possible exception
433 are given to the completion callback.
435 Only available on Mac OS X.
437 ## fs.lchmodSync(path, mode)
439 Synchronous lchmod(2). Returns `undefined`.
441 ## fs.lchown(path, uid, gid, callback)
443 Asynchronous lchown(2). No arguments other than a possible exception are given
444 to the completion callback.
446 ## fs.lchownSync(path, uid, gid)
448 Synchronous lchown(2). Returns `undefined`.
450 ## fs.link(srcpath, dstpath, callback)
452 Asynchronous link(2). No arguments other than a possible exception are given to
453 the completion callback.
455 ## fs.linkSync(srcpath, dstpath)
457 Synchronous link(2). Returns `undefined`.
459 ## fs.lstat(path, callback)
461 Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where
462 `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if
463 `path` is a symbolic link, then the link itself is stat-ed, not the file that it
466 ## fs.lstatSync(path)
468 Synchronous lstat(2). Returns an instance of `fs.Stats`.
470 ## fs.mkdir(path[, mode], callback)
472 Asynchronous mkdir(2). No arguments other than a possible exception are given
473 to the completion callback. `mode` defaults to `0o777`.
475 ## fs.mkdirSync(path[, mode])
477 Synchronous mkdir(2). Returns `undefined`.
479 ## fs.open(path, flags[, mode], callback)
481 Asynchronous file open. See open(2). `flags` can be:
483 * `'r'` - Open file for reading.
484 An exception occurs if the file does not exist.
486 * `'r+'` - Open file for reading and writing.
487 An exception occurs if the file does not exist.
489 * `'rs'` - Open file for reading in synchronous mode. Instructs the operating
490 system to bypass the local file system cache.
492 This is primarily useful for opening files on NFS mounts as it allows you to
493 skip the potentially stale local cache. It has a very real impact on I/O
494 performance so don't use this flag unless you need it.
496 Note that this doesn't turn `fs.open()` into a synchronous blocking call.
497 If that's what you want then you should be using `fs.openSync()`
499 * `'rs+'` - Open file for reading and writing, telling the OS to open it
500 synchronously. See notes for `'rs'` about using this with caution.
502 * `'w'` - Open file for writing.
503 The file is created (if it does not exist) or truncated (if it exists).
505 * `'wx'` - Like `'w'` but fails if `path` exists.
507 * `'w+'` - Open file for reading and writing.
508 The file is created (if it does not exist) or truncated (if it exists).
510 * `'wx+'` - Like `'w+'` but fails if `path` exists.
512 * `'a'` - Open file for appending.
513 The file is created if it does not exist.
515 * `'ax'` - Like `'a'` but fails if `path` exists.
517 * `'a+'` - Open file for reading and appending.
518 The file is created if it does not exist.
520 * `'ax+'` - Like `'a+'` but fails if `path` exists.
522 `mode` sets the file mode (permission and sticky bits), but only if the file was
523 created. It defaults to `0666`, readable and writeable.
525 The callback gets two arguments `(err, fd)`.
527 The exclusive flag `'x'` (`O_EXCL` flag in open(2)) ensures that `path` is newly
528 created. On POSIX systems, `path` is considered to exist even if it is a symlink
529 to a non-existent file. The exclusive flag may or may not work with network file
532 On Linux, positional writes don't work when the file is opened in append mode.
533 The kernel ignores the position argument and always appends the data to
536 ## fs.openSync(path, flags[, mode])
538 Synchronous version of `fs.open()`. Returns an integer representing the file
541 ## fs.read(fd, buffer, offset, length, position, callback)
543 Read data from the file specified by `fd`.
545 `buffer` is the buffer that the data will be written to.
547 `offset` is the offset in the buffer to start writing at.
549 `length` is an integer specifying the number of bytes to read.
551 `position` is an integer specifying where to begin reading from in the file.
552 If `position` is `null`, data will be read from the current file position.
554 The callback is given the three arguments, `(err, bytesRead, buffer)`.
556 ## fs.readdir(path, callback)
558 Asynchronous readdir(3). Reads the contents of a directory.
559 The callback gets two arguments `(err, files)` where `files` is an array of
560 the names of the files in the directory excluding `'.'` and `'..'`.
562 ## fs.readdirSync(path)
564 Synchronous readdir(3). Returns an array of filenames excluding `'.'` and
567 ## fs.readFile(file[, options], callback)
569 * `file` {String | Integer} filename or file descriptor
570 * `options` {Object | String}
571 * `encoding` {String | Null} default = `null`
572 * `flag` {String} default = `'r'`
573 * `callback` {Function}
575 Asynchronously reads the entire contents of a file. Example:
577 fs.readFile('/etc/passwd', function (err, data) {
582 The callback is passed two arguments `(err, data)`, where `data` is the
583 contents of the file.
585 If no encoding is specified, then the raw buffer is returned.
587 If `options` is a string, then it specifies the encoding. Example:
589 fs.readFile('/etc/passwd', 'utf8', callback);
591 Any specified file descriptor has to support reading.
593 _Note: Specified file descriptors will not be closed automatically._
595 ## fs.readFileSync(file[, options])
597 Synchronous version of `fs.readFile`. Returns the contents of the `file`.
599 If the `encoding` option is specified then this function returns a
600 string. Otherwise it returns a buffer.
602 ## fs.readlink(path, callback)
604 Asynchronous readlink(2). The callback gets two arguments `(err,
607 ## fs.readlinkSync(path)
609 Synchronous readlink(2). Returns the symbolic link's string value.
611 ## fs.realpath(path[, cache], callback)
613 Asynchronous realpath(2). The `callback` gets two arguments `(err,
614 resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an
615 object literal of mapped paths that can be used to force a specific path
616 resolution or avoid additional `fs.stat` calls for known real paths.
620 var cache = {'/etc':'/private/etc'};
621 fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
623 console.log(resolvedPath);
626 ## fs.readSync(fd, buffer, offset, length, position)
628 Synchronous version of `fs.read`. Returns the number of `bytesRead`.
630 ## fs.realpathSync(path[, cache])
632 Synchronous realpath(2). Returns the resolved path.
634 ## fs.rename(oldPath, newPath, callback)
636 Asynchronous rename(2). No arguments other than a possible exception are given
637 to the completion callback.
639 ## fs.renameSync(oldPath, newPath)
641 Synchronous rename(2). Returns `undefined`.
643 ## fs.rmdir(path, callback)
645 Asynchronous rmdir(2). No arguments other than a possible exception are given
646 to the completion callback.
648 ## fs.rmdirSync(path)
650 Synchronous rmdir(2). Returns `undefined`.
652 ## fs.stat(path, callback)
654 Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
655 `stats` is a [fs.Stats](#fs_class_fs_stats) object. See the [fs.Stats](#fs_class_fs_stats)
656 section below for more information.
660 Synchronous stat(2). Returns an instance of `fs.Stats`.
662 ## fs.symlink(destination, path[, type], callback)
664 Asynchronous symlink(2). No arguments other than a possible exception are given
665 to the completion callback.
666 The `type` argument can be set to `'dir'`, `'file'`, or `'junction'` (default
667 is `'file'`) and is only available on Windows (ignored on other platforms).
668 Note that Windows junction points require the destination path to be absolute. When using
669 `'junction'`, the `destination` argument will automatically be normalized to absolute path.
671 ## fs.symlinkSync(destination, path[, type])
673 Synchronous symlink(2). Returns `undefined`.
675 ## fs.truncate(path, len, callback)
677 Asynchronous truncate(2). No arguments other than a possible exception are
678 given to the completion callback. A file descriptor can also be passed as the
679 first argument. In this case, `fs.ftruncate()` is called.
681 ## fs.truncateSync(path, len)
683 Synchronous truncate(2). Returns `undefined`.
685 ## fs.unlink(path, callback)
687 Asynchronous unlink(2). No arguments other than a possible exception are given
688 to the completion callback.
690 ## fs.unlinkSync(path)
692 Synchronous unlink(2). Returns `undefined`.
694 ## fs.unwatchFile(filename[, listener])
696 Stop watching for changes on `filename`. If `listener` is specified, only that
697 particular listener is removed. Otherwise, *all* listeners are removed and you
698 have effectively stopped watching `filename`.
700 Calling `fs.unwatchFile()` with a filename that is not being watched is a
703 _Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`.
704 `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile`
707 ## fs.utimes(path, atime, mtime, callback)
709 Change file timestamps of the file referenced by the supplied path.
711 Note: the arguments `atime` and `mtime` of the following related functions does
712 follow the below rules:
714 - If the value is a numberable string like "123456789", the value would get
715 converted to corresponding number.
716 - If the value is `NaN` or `Infinity`, the value would get converted to
719 ## fs.utimesSync(path, atime, mtime)
721 Synchronous version of `fs.utimes()`. Returns `undefined`.
723 ## fs.watch(filename[, options][, listener])
725 Watch for changes on `filename`, where `filename` is either a file or a
726 directory. The returned object is a [fs.FSWatcher](#fs_class_fs_fswatcher).
728 The second argument is optional. The `options` if provided should be an object.
729 The supported boolean members are `persistent` and `recursive`. `persistent`
730 indicates whether the process should continue to run as long as files are being
731 watched. `recursive` indicates whether all subdirectories should be watched, or
732 only the current directory. This applies when a directory is specified, and only
733 on supported platforms (See Caveats below).
735 The default is `{ persistent: true, recursive: false }`.
737 The listener callback gets two arguments `(event, filename)`. `event` is either
738 'rename' or 'change', and `filename` is the name of the file which triggered
745 The `fs.watch` API is not 100% consistent across platforms, and is
746 unavailable in some situations.
748 The recursive option is only supported on OS X and Windows.
754 This feature depends on the underlying operating system providing a way
755 to be notified of filesystem changes.
757 * On Linux systems, this uses `inotify`.
758 * On BSD systems, this uses `kqueue`.
759 * On OS X, this uses `kqueue` for files and 'FSEvents' for directories.
760 * On SunOS systems (including Solaris and SmartOS), this uses `event ports`.
761 * On Windows systems, this feature depends on `ReadDirectoryChangesW`.
763 If the underlying functionality is not available for some reason, then
764 `fs.watch` will not be able to function. For example, watching files or
765 directories on network file systems (NFS, SMB, etc.) often doesn't work
768 You can still use `fs.watchFile`, which uses stat polling, but it is slower and
771 #### Filename Argument
775 Providing `filename` argument in the callback is only supported on Linux and
776 Windows. Even on supported platforms, `filename` is not always guaranteed to
777 be provided. Therefore, don't assume that `filename` argument is always
778 provided in the callback, and have some fallback logic if it is null.
780 fs.watch('somedir', function (event, filename) {
781 console.log('event is: ' + event);
783 console.log('filename provided: ' + filename);
785 console.log('filename not provided');
789 ## fs.watchFile(filename[, options], listener)
791 Watch for changes on `filename`. The callback `listener` will be called each
792 time the file is accessed.
794 The `options` argument may be omitted. If provided, it should be an object. The
795 `options` object may contain a boolean named `persistent` that indicates
796 whether the process should continue to run as long as files are being watched.
797 The `options` object may specify an `interval` property indicating how often the
798 target should be polled in milliseconds. The default is
799 `{ persistent: true, interval: 5007 }`.
801 The `listener` gets two arguments the current stat object and the previous
804 fs.watchFile('message.text', function (curr, prev) {
805 console.log('the current mtime is: ' + curr.mtime);
806 console.log('the previous mtime was: ' + prev.mtime);
809 These stat objects are instances of `fs.Stat`.
811 If you want to be notified when the file was modified, not just accessed,
812 you need to compare `curr.mtime` and `prev.mtime`.
814 _Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will
815 invoke the listener once, with all the fields zeroed (or, for dates, the Unix
816 Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead
817 of zero. If the file is created later on, the listener will be called again,
818 with the latest stat objects. This is a change in functionality since v0.10._
820 _Note: `fs.watch` is more efficient than `fs.watchFile` and `fs.unwatchFile`.
821 `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile`
824 ## fs.write(fd, buffer, offset, length[, position], callback)
826 Write `buffer` to the file specified by `fd`.
828 `offset` and `length` determine the part of the buffer to be written.
830 `position` refers to the offset from the beginning of the file where this data
831 should be written. If `typeof position !== 'number'`, the data will be written
832 at the current position. See pwrite(2).
834 The callback will be given three arguments `(err, written, buffer)` where
835 `written` specifies how many _bytes_ were written from `buffer`.
837 Note that it is unsafe to use `fs.write` multiple times on the same file
838 without waiting for the callback. For this scenario,
839 `fs.createWriteStream` is strongly recommended.
841 On Linux, positional writes don't work when the file is opened in append mode.
842 The kernel ignores the position argument and always appends the data to
845 ## fs.write(fd, data[, position[, encoding]], callback)
847 Write `data` to the file specified by `fd`. If `data` is not a Buffer instance
848 then the value will be coerced to a string.
850 `position` refers to the offset from the beginning of the file where this data
851 should be written. If `typeof position !== 'number'` the data will be written at
852 the current position. See pwrite(2).
854 `encoding` is the expected string encoding.
856 The callback will receive the arguments `(err, written, string)` where `written`
857 specifies how many _bytes_ the passed string required to be written. Note that
858 bytes written is not the same as string characters. See
859 [Buffer.byteLength](buffer.html#buffer_class_method_buffer_bytelength_string_encoding).
861 Unlike when writing `buffer`, the entire string must be written. No substring
862 may be specified. This is because the byte offset of the resulting data may not
863 be the same as the string offset.
865 Note that it is unsafe to use `fs.write` multiple times on the same file
866 without waiting for the callback. For this scenario,
867 `fs.createWriteStream` is strongly recommended.
869 On Linux, positional writes don't work when the file is opened in append mode.
870 The kernel ignores the position argument and always appends the data to
873 ## fs.writeFile(file, data[, options], callback)
875 * `file` {String | Integer} filename or file descriptor
876 * `data` {String | Buffer}
877 * `options` {Object | String}
878 * `encoding` {String | Null} default = `'utf8'`
879 * `mode` {Number} default = `0o666`
880 * `flag` {String} default = `'w'`
881 * `callback` {Function}
883 Asynchronously writes data to a file, replacing the file if it already exists.
884 `data` can be a string or a buffer.
886 The `encoding` option is ignored if `data` is a buffer. It defaults
891 fs.writeFile('message.txt', 'Hello Node.js', function (err) {
893 console.log('It\'s saved!');
896 If `options` is a string, then it specifies the encoding. Example:
898 fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
900 Any specified file descriptor has to support writing.
902 Note that it is unsafe to use `fs.writeFile` multiple times on the same file
903 without waiting for the callback. For this scenario,
904 `fs.createWriteStream` is strongly recommended.
906 _Note: Specified file descriptors will not be closed automatically._
908 ## fs.writeFileSync(file, data[, options])
910 The synchronous version of `fs.writeFile`. Returns `undefined`.
912 ## fs.writeSync(fd, buffer, offset, length[, position])
914 ## fs.writeSync(fd, data[, position[, encoding]])
916 Synchronous versions of `fs.write()`. Returns the number of bytes written.
918 [fs.stat]: #fs_fs_stat_path_callback
919 [fs.access]: #fs_fs_access_path_mode_callback
920 [fs.statSync]: #fs_fs_statsync_path
921 [fs.accessSync]: #fs_fs_accesssync_path_mode
922 [Buffer]: buffer.html#buffer_buffer