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 const fs = require('fs');
23 fs.unlink('/tmp/hello', (err) => {
25 console.log('successfully deleted /tmp/hello');
28 Here is the synchronous version:
30 const 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', (err) => {
40 console.log('renamed complete');
42 fs.stat('/tmp/world', (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', (err) => {
52 fs.stat('/tmp/world', (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()`][].
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][].
115 * `fd` {Integer} file descriptor used by the ReadStream.
117 Emitted when the ReadStream's file is opened.
121 The path to the file the stream is reading from.
125 Objects returned from [`fs.stat()`][], [`fs.lstat()`][] and [`fs.fstat()`][] and their
126 synchronous counterparts are of this type.
129 - `stats.isDirectory()`
130 - `stats.isBlockDevice()`
131 - `stats.isCharacterDevice()`
132 - `stats.isSymbolicLink()` (only valid with [`fs.lstat()`][])
136 For a regular file [`util.inspect(stats)`][] would return a string very
149 atime: Mon, 10 Oct 2011 23:24:11 GMT,
150 mtime: Mon, 10 Oct 2011 23:24:11 GMT,
151 ctime: Mon, 10 Oct 2011 23:24:11 GMT,
152 birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
154 Please note that `atime`, `mtime`, `birthtime`, and `ctime` are
155 instances of [`Date`][MDN-Date] object and to compare the values of
156 these objects you should use appropriate methods. For most general
157 uses [`getTime()`][MDN-Date-getTime] will return the number of
158 milliseconds elapsed since _1 January 1970 00:00:00 UTC_ and this
159 integer should be sufficient for any comparison, however there are
160 additional methods which can be used for displaying fuzzy information.
161 More details can be found in the [MDN JavaScript Reference][MDN-Date]
166 The times in the stat object have the following semantics:
168 * `atime` "Access Time" - Time when file data last accessed. Changed
169 by the `mknod(2)`, `utimes(2)`, and `read(2)` system calls.
170 * `mtime` "Modified Time" - Time when file data last modified.
171 Changed by the `mknod(2)`, `utimes(2)`, and `write(2)` system calls.
172 * `ctime` "Change Time" - Time when file status was last changed
173 (inode data modification). Changed by the `chmod(2)`, `chown(2)`,
174 `link(2)`, `mknod(2)`, `rename(2)`, `unlink(2)`, `utimes(2)`,
175 `read(2)`, and `write(2)` system calls.
176 * `birthtime` "Birth Time" - Time of file creation. Set once when the
177 file is created. On filesystems where birthtime is not available,
178 this field may instead hold either the `ctime` or
179 `1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). On Darwin and
180 other FreeBSD variants, also set if the `atime` is explicitly set to
181 an earlier value than the current `birthtime` using the `utimes(2)`
184 Prior to Node v0.12, the `ctime` held the `birthtime` on Windows
185 systems. Note that as of v0.12, `ctime` is not "creation time", and
186 on Unix systems, it never was.
188 ## Class: fs.WriteStream
190 `WriteStream` is a [Writable Stream][].
194 * `fd` {Integer} file descriptor used by the WriteStream.
196 Emitted when the WriteStream's file is opened.
198 ### writeStream.bytesWritten
200 The number of bytes written so far. Does not include data that is still queued
205 The path to the file the stream is writing to.
207 ## fs.access(path[, mode], callback)
209 Tests a user's permissions for the file specified by `path`. `mode` is an
210 optional integer that specifies the accessibility checks to be performed. The
211 following constants define the possible values of `mode`. It is possible to
212 create a mask consisting of the bitwise OR of two or more values.
214 - `fs.F_OK` - File is visible to the calling process. This is useful for
215 determining if a file exists, but says nothing about `rwx` permissions.
216 Default if no `mode` is specified.
217 - `fs.R_OK` - File can be read by the calling process.
218 - `fs.W_OK` - File can be written by the calling process.
219 - `fs.X_OK` - File can be executed by the calling process. This has no effect
220 on Windows (will behave like `fs.F_OK`).
222 The final argument, `callback`, is a callback function that is invoked with
223 a possible error argument. If any of the accessibility checks fail, the error
224 argument will be populated. The following example checks if the file
225 `/etc/passwd` can be read and written by the current process.
227 fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) {
228 console.log(err ? 'no access!' : 'can read/write');
231 ## fs.accessSync(path[, mode])
233 Synchronous version of [`fs.access()`][]. This throws if any accessibility checks
234 fail, and does nothing otherwise.
236 ## fs.appendFile(file, data[, options], callback)
238 * `file` {String | Integer} filename or file descriptor
239 * `data` {String | Buffer}
240 * `options` {Object | String}
241 * `encoding` {String | Null} default = `'utf8'`
242 * `mode` {Number} default = `0o666`
243 * `flag` {String} default = `'a'`
244 * `callback` {Function}
246 Asynchronously append data to a file, creating the file if it does not yet exist.
247 `data` can be a string or a buffer.
251 fs.appendFile('message.txt', 'data to append', (err) => {
253 console.log('The "data to append" was appended to file!');
256 If `options` is a string, then it specifies the encoding. Example:
258 fs.appendFile('message.txt', 'data to append', 'utf8', callback);
260 Any specified file descriptor has to have been opened for appending.
262 _Note: Specified file descriptors will not be closed automatically._
264 ## fs.appendFileSync(file, data[, options])
266 The synchronous version of [`fs.appendFile()`][]. Returns `undefined`.
268 ## fs.chmod(path, mode, callback)
270 Asynchronous chmod(2). No arguments other than a possible exception are given
271 to the completion callback.
273 ## fs.chmodSync(path, mode)
275 Synchronous chmod(2). Returns `undefined`.
277 ## fs.chown(path, uid, gid, callback)
279 Asynchronous chown(2). No arguments other than a possible exception are given
280 to the completion callback.
282 ## fs.chownSync(path, uid, gid)
284 Synchronous chown(2). Returns `undefined`.
286 ## fs.close(fd, callback)
288 Asynchronous close(2). No arguments other than a possible exception are given
289 to the completion callback.
293 Synchronous close(2). Returns `undefined`.
295 ## fs.createReadStream(path[, options])
297 Returns a new [`ReadStream`][] object. (See [Readable Stream][]).
299 Be aware that, unlike the default value set for `highWaterMark` on a
300 readable stream (16 kb), the stream returned by this method has a
301 default value of 64 kb for the same parameter.
303 `options` is an object or string with the following defaults:
312 `options` can include `start` and `end` values to read a range of bytes from
313 the file instead of the entire file. Both `start` and `end` are inclusive and
314 start at 0. The `encoding` can be any one of those accepted by [`Buffer`][].
316 If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
317 the specified file descriptor. This means that no `'open'` event will be emitted.
318 Note that `fd` should be blocking; non-blocking `fd`s should be passed to
321 If `autoClose` is false, then the file descriptor won't be closed, even if
322 there's an error. It is your responsibility to close it and make sure
323 there's no file descriptor leak. If `autoClose` is set to true (default
324 behavior), on `error` or `end` the file descriptor will be closed
327 `mode` sets the file mode (permission and sticky bits), but only if the
330 An example to read the last 10 bytes of a file which is 100 bytes long:
332 fs.createReadStream('sample.txt', {start: 90, end: 99});
334 If `options` is a string, then it specifies the encoding.
336 ## fs.createWriteStream(path[, options])
338 Returns a new [`WriteStream`][] object. (See [Writable Stream][]).
340 `options` is an object or string with the following defaults:
343 defaultEncoding: 'utf8',
347 `options` may also include a `start` option to allow writing data at
348 some position past the beginning of the file. Modifying a file rather
349 than replacing it may require a `flags` mode of `r+` rather than the
350 default mode `w`. The `defaultEncoding` can be any one of those accepted by [`Buffer`][].
352 Like [`ReadStream`][], if `fd` is specified, `WriteStream` will ignore the
353 `path` argument and will use the specified file descriptor. This means that no
354 `'open'` event will be emitted. Note that `fd` should be blocking; non-blocking
355 `fd`s should be passed to [`net.Socket`][].
357 If `options` is a string, then it specifies the encoding.
359 ## fs.exists(path, callback)
361 Stability: 0 - Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.
363 Test whether or not the given path exists by checking with the file system.
364 Then call the `callback` argument with either true or false. Example:
366 fs.exists('/etc/passwd', (exists) => {
367 console.log(exists ? 'it\'s there' : 'no passwd!');
370 `fs.exists()` should not be used to check if a file exists before calling
371 `fs.open()`. Doing so introduces a race condition since other processes may
372 change the file's state between the two calls. Instead, user code should
373 call `fs.open()` directly and handle the error raised if the file is
376 ## fs.existsSync(path)
378 Stability: 0 - Deprecated: Use [`fs.statSync()`][] or [`fs.accessSync()`][] instead.
380 Synchronous version of [`fs.exists()`][].
381 Returns `true` if the file exists, `false` otherwise.
383 ## fs.fchmod(fd, mode, callback)
385 Asynchronous fchmod(2). No arguments other than a possible exception
386 are given to the completion callback.
388 ## fs.fchmodSync(fd, mode)
390 Synchronous fchmod(2). Returns `undefined`.
392 ## fs.fchown(fd, uid, gid, callback)
394 Asynchronous fchown(2). No arguments other than a possible exception are given
395 to the completion callback.
397 ## fs.fchownSync(fd, uid, gid)
399 Synchronous fchown(2). Returns `undefined`.
401 ## fs.fstat(fd, callback)
403 Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
404 `stats` is a `fs.Stats` object. `fstat()` is identical to [`stat()`][], except that
405 the file to be stat-ed is specified by the file descriptor `fd`.
409 Synchronous fstat(2). Returns an instance of `fs.Stats`.
411 ## fs.fsync(fd, callback)
413 Asynchronous fsync(2). No arguments other than a possible exception are given
414 to the completion callback.
418 Synchronous fsync(2). Returns `undefined`.
420 ## fs.ftruncate(fd, len, callback)
422 Asynchronous ftruncate(2). No arguments other than a possible exception are
423 given to the completion callback.
425 ## fs.ftruncateSync(fd, len)
427 Synchronous ftruncate(2). Returns `undefined`.
429 ## fs.futimes(fd, atime, mtime, callback)
431 Change the file timestamps of a file referenced by the supplied file
434 ## fs.futimesSync(fd, atime, mtime)
436 Synchronous version of [`fs.futimes()`][]. Returns `undefined`.
438 ## fs.lchmod(path, mode, callback)
440 Asynchronous lchmod(2). No arguments other than a possible exception
441 are given to the completion callback.
443 Only available on Mac OS X.
445 ## fs.lchmodSync(path, mode)
447 Synchronous lchmod(2). Returns `undefined`.
449 ## fs.lchown(path, uid, gid, callback)
451 Asynchronous lchown(2). No arguments other than a possible exception are given
452 to the completion callback.
454 ## fs.lchownSync(path, uid, gid)
456 Synchronous lchown(2). Returns `undefined`.
458 ## fs.link(srcpath, dstpath, callback)
460 Asynchronous link(2). No arguments other than a possible exception are given to
461 the completion callback.
463 ## fs.linkSync(srcpath, dstpath)
465 Synchronous link(2). Returns `undefined`.
467 ## fs.lstat(path, callback)
469 Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where
470 `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if
471 `path` is a symbolic link, then the link itself is stat-ed, not the file that it
474 ## fs.lstatSync(path)
476 Synchronous lstat(2). Returns an instance of `fs.Stats`.
478 ## fs.mkdir(path[, mode], callback)
480 Asynchronous mkdir(2). No arguments other than a possible exception are given
481 to the completion callback. `mode` defaults to `0o777`.
483 ## fs.mkdirSync(path[, mode])
485 Synchronous mkdir(2). Returns `undefined`.
487 ## fs.open(path, flags[, mode], callback)
489 Asynchronous file open. See open(2). `flags` can be:
491 * `'r'` - Open file for reading.
492 An exception occurs if the file does not exist.
494 * `'r+'` - Open file for reading and writing.
495 An exception occurs if the file does not exist.
497 * `'rs'` - Open file for reading in synchronous mode. Instructs the operating
498 system to bypass the local file system cache.
500 This is primarily useful for opening files on NFS mounts as it allows you to
501 skip the potentially stale local cache. It has a very real impact on I/O
502 performance so don't use this flag unless you need it.
504 Note that this doesn't turn `fs.open()` into a synchronous blocking call.
505 If that's what you want then you should be using `fs.openSync()`
507 * `'rs+'` - Open file for reading and writing, telling the OS to open it
508 synchronously. See notes for `'rs'` about using this with caution.
510 * `'w'` - Open file for writing.
511 The file is created (if it does not exist) or truncated (if it exists).
513 * `'wx'` - Like `'w'` but fails if `path` exists.
515 * `'w+'` - Open file for reading and writing.
516 The file is created (if it does not exist) or truncated (if it exists).
518 * `'wx+'` - Like `'w+'` but fails if `path` exists.
520 * `'a'` - Open file for appending.
521 The file is created if it does not exist.
523 * `'ax'` - Like `'a'` but fails if `path` exists.
525 * `'a+'` - Open file for reading and appending.
526 The file is created if it does not exist.
528 * `'ax+'` - Like `'a+'` but fails if `path` exists.
530 `mode` sets the file mode (permission and sticky bits), but only if the file was
531 created. It defaults to `0666`, readable and writable.
533 The callback gets two arguments `(err, fd)`.
535 The exclusive flag `'x'` (`O_EXCL` flag in open(2)) ensures that `path` is newly
536 created. On POSIX systems, `path` is considered to exist even if it is a symlink
537 to a non-existent file. The exclusive flag may or may not work with network file
540 `flags` can also be a number as documented by open(2); commonly used constants
541 are available from `require('constants')`. On Windows, flags are translated to
542 their equivalent ones where applicable, e.g. `O_WRONLY` to `FILE_GENERIC_WRITE`,
543 or `O_EXCL|O_CREAT` to `CREATE_NEW`, as accepted by CreateFileW.
545 On Linux, positional writes don't work when the file is opened in append mode.
546 The kernel ignores the position argument and always appends the data to
549 ## fs.openSync(path, flags[, mode])
551 Synchronous version of [`fs.open()`][]. Returns an integer representing the file
554 ## fs.read(fd, buffer, offset, length, position, callback)
556 Read data from the file specified by `fd`.
558 `buffer` is the buffer that the data will be written to.
560 `offset` is the offset in the buffer to start writing at.
562 `length` is an integer specifying the number of bytes to read.
564 `position` is an integer specifying where to begin reading from in the file.
565 If `position` is `null`, data will be read from the current file position.
567 The callback is given the three arguments, `(err, bytesRead, buffer)`.
569 ## fs.readdir(path, callback)
571 Asynchronous readdir(3). Reads the contents of a directory.
572 The callback gets two arguments `(err, files)` where `files` is an array of
573 the names of the files in the directory excluding `'.'` and `'..'`.
575 ## fs.readdirSync(path)
577 Synchronous readdir(3). Returns an array of filenames excluding `'.'` and
580 ## fs.readFile(file[, options], callback)
582 * `file` {String | Integer} filename or file descriptor
583 * `options` {Object | String}
584 * `encoding` {String | Null} default = `null`
585 * `flag` {String} default = `'r'`
586 * `callback` {Function}
588 Asynchronously reads the entire contents of a file. Example:
590 fs.readFile('/etc/passwd', (err, data) => {
595 The callback is passed two arguments `(err, data)`, where `data` is the
596 contents of the file.
598 If no encoding is specified, then the raw buffer is returned.
600 If `options` is a string, then it specifies the encoding. Example:
602 fs.readFile('/etc/passwd', 'utf8', callback);
604 Any specified file descriptor has to support reading.
606 _Note: Specified file descriptors will not be closed automatically._
608 ## fs.readFileSync(file[, options])
610 Synchronous version of [`fs.readFile`][]. Returns the contents of the `file`.
612 If the `encoding` option is specified then this function returns a
613 string. Otherwise it returns a buffer.
615 ## fs.readlink(path, callback)
617 Asynchronous readlink(2). The callback gets two arguments `(err,
620 ## fs.readlinkSync(path)
622 Synchronous readlink(2). Returns the symbolic link's string value.
624 ## fs.realpath(path[, cache], callback)
626 Asynchronous realpath(2). The `callback` gets two arguments `(err,
627 resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an
628 object literal of mapped paths that can be used to force a specific path
629 resolution or avoid additional `fs.stat` calls for known real paths.
633 var cache = {'/etc':'/private/etc'};
634 fs.realpath('/etc/passwd', cache, (err, resolvedPath) => {
636 console.log(resolvedPath);
639 ## fs.readSync(fd, buffer, offset, length, position)
641 Synchronous version of [`fs.read()`][]. Returns the number of `bytesRead`.
643 ## fs.realpathSync(path[, cache])
645 Synchronous realpath(2). Returns the resolved path. `cache` is an
646 object literal of mapped paths that can be used to force a specific path
647 resolution or avoid additional `fs.stat` calls for known real paths.
649 ## fs.rename(oldPath, newPath, callback)
651 Asynchronous rename(2). No arguments other than a possible exception are given
652 to the completion callback.
654 ## fs.renameSync(oldPath, newPath)
656 Synchronous rename(2). Returns `undefined`.
658 ## fs.rmdir(path, callback)
660 Asynchronous rmdir(2). No arguments other than a possible exception are given
661 to the completion callback.
663 ## fs.rmdirSync(path)
665 Synchronous rmdir(2). Returns `undefined`.
667 ## fs.stat(path, callback)
669 Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
670 `stats` is a [`fs.Stats`][] object. See the [`fs.Stats`][] section for more
675 Synchronous stat(2). Returns an instance of [`fs.Stats`][].
677 ## fs.symlink(target, path[, type], callback)
679 Asynchronous symlink(2). No arguments other than a possible exception are given
680 to the completion callback.
681 The `type` argument can be set to `'dir'`, `'file'`, or `'junction'` (default
682 is `'file'`) and is only available on Windows (ignored on other platforms).
683 Note that Windows junction points require the destination path to be absolute. When using
684 `'junction'`, the `target` argument will automatically be normalized to absolute path.
686 Here is an example below:
688 fs.symlink('./foo', './new-port');
690 It would create a symlic link named with "new-port" that points to "foo".
692 ## fs.symlinkSync(target, path[, type])
694 Synchronous symlink(2). Returns `undefined`.
696 ## fs.truncate(path, len, callback)
698 Asynchronous truncate(2). No arguments other than a possible exception are
699 given to the completion callback. A file descriptor can also be passed as the
700 first argument. In this case, `fs.ftruncate()` is called.
702 ## fs.truncateSync(path, len)
704 Synchronous truncate(2). Returns `undefined`.
706 ## fs.unlink(path, callback)
708 Asynchronous unlink(2). No arguments other than a possible exception are given
709 to the completion callback.
711 ## fs.unlinkSync(path)
713 Synchronous unlink(2). Returns `undefined`.
715 ## fs.unwatchFile(filename[, listener])
717 Stop watching for changes on `filename`. If `listener` is specified, only that
718 particular listener is removed. Otherwise, *all* listeners are removed and you
719 have effectively stopped watching `filename`.
721 Calling `fs.unwatchFile()` with a filename that is not being watched is a
724 _Note: [`fs.watch()`][] is more efficient than `fs.watchFile()` and `fs.unwatchFile()`.
725 `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()`
728 ## fs.utimes(path, atime, mtime, callback)
730 Change file timestamps of the file referenced by the supplied path.
732 Note: the arguments `atime` and `mtime` of the following related functions does
733 follow the below rules:
735 - If the value is a numberable string like `'123456789'`, the value would get
736 converted to corresponding number.
737 - If the value is `NaN` or `Infinity`, the value would get converted to
740 ## fs.utimesSync(path, atime, mtime)
742 Synchronous version of [`fs.utimes()`][]. Returns `undefined`.
744 ## fs.watch(filename[, options][, listener])
746 Watch for changes on `filename`, where `filename` is either a file or a
747 directory. The returned object is a [`fs.FSWatcher`][].
749 The second argument is optional. The `options` if provided should be an object.
750 The supported boolean members are `persistent` and `recursive`. `persistent`
751 indicates whether the process should continue to run as long as files are being
752 watched. `recursive` indicates whether all subdirectories should be watched, or
753 only the current directory. This applies when a directory is specified, and only
754 on supported platforms (See [Caveats][]).
756 The default is `{ persistent: true, recursive: false }`.
758 The listener callback gets two arguments `(event, filename)`. `event` is either
759 `'rename'` or `'change'`, and `filename` is the name of the file which triggered
766 The `fs.watch` API is not 100% consistent across platforms, and is
767 unavailable in some situations.
769 The recursive option is only supported on OS X and Windows.
775 This feature depends on the underlying operating system providing a way
776 to be notified of filesystem changes.
778 * On Linux systems, this uses `inotify`.
779 * On BSD systems, this uses `kqueue`.
780 * On OS X, this uses `kqueue` for files and 'FSEvents' for directories.
781 * On SunOS systems (including Solaris and SmartOS), this uses `event ports`.
782 * On Windows systems, this feature depends on `ReadDirectoryChangesW`.
784 If the underlying functionality is not available for some reason, then
785 `fs.watch` will not be able to function. For example, watching files or
786 directories on network file systems (NFS, SMB, etc.) often doesn't work
789 You can still use `fs.watchFile`, which uses stat polling, but it is slower and
792 #### Filename Argument
796 Providing `filename` argument in the callback is only supported on Linux and
797 Windows. Even on supported platforms, `filename` is not always guaranteed to
798 be provided. Therefore, don't assume that `filename` argument is always
799 provided in the callback, and have some fallback logic if it is null.
801 fs.watch('somedir', (event, filename) => {
802 console.log(`event is: ${event}`);
804 console.log(`filename provided: ${filename}`);
806 console.log('filename not provided');
810 ## fs.watchFile(filename[, options], listener)
812 Watch for changes on `filename`. The callback `listener` will be called each
813 time the file is accessed.
815 The `options` argument may be omitted. If provided, it should be an object. The
816 `options` object may contain a boolean named `persistent` that indicates
817 whether the process should continue to run as long as files are being watched.
818 The `options` object may specify an `interval` property indicating how often the
819 target should be polled in milliseconds. The default is
820 `{ persistent: true, interval: 5007 }`.
822 The `listener` gets two arguments the current stat object and the previous
825 fs.watchFile('message.text', (curr, prev) => {
826 console.log(`the current mtime is: ${curr.mtime}`);
827 console.log(`the previous mtime was: ${prev.mtime}`);
830 These stat objects are instances of `fs.Stat`.
832 If you want to be notified when the file was modified, not just accessed,
833 you need to compare `curr.mtime` and `prev.mtime`.
835 _Note: when an `fs.watchFile` operation results in an `ENOENT` error, it will
836 invoke the listener once, with all the fields zeroed (or, for dates, the Unix
837 Epoch). In Windows, `blksize` and `blocks` fields will be `undefined`, instead
838 of zero. If the file is created later on, the listener will be called again,
839 with the latest stat objects. This is a change in functionality since v0.10._
841 _Note: [`fs.watch()`][] is more efficient than `fs.watchFile` and `fs.unwatchFile`.
842 `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile`
845 ## fs.write(fd, buffer, offset, length[, position], callback)
847 Write `buffer` to the file specified by `fd`.
849 `offset` and `length` determine the part of the buffer to be written.
851 `position` refers to the offset from the beginning of the file where this data
852 should be written. If `typeof position !== 'number'`, the data will be written
853 at the current position. See pwrite(2).
855 The callback will be given three arguments `(err, written, buffer)` where
856 `written` specifies how many _bytes_ were written from `buffer`.
858 Note that it is unsafe to use `fs.write` multiple times on the same file
859 without waiting for the callback. For this scenario,
860 `fs.createWriteStream` is strongly recommended.
862 On Linux, positional writes don't work when the file is opened in append mode.
863 The kernel ignores the position argument and always appends the data to
866 ## fs.write(fd, data[, position[, encoding]], callback)
868 Write `data` to the file specified by `fd`. If `data` is not a Buffer instance
869 then the value will be coerced to a string.
871 `position` refers to the offset from the beginning of the file where this data
872 should be written. If `typeof position !== 'number'` the data will be written at
873 the current position. See pwrite(2).
875 `encoding` is the expected string encoding.
877 The callback will receive the arguments `(err, written, string)` where `written`
878 specifies how many _bytes_ the passed string required to be written. Note that
879 bytes written is not the same as string characters. See [`Buffer.byteLength`][].
881 Unlike when writing `buffer`, the entire string must be written. No substring
882 may be specified. This is because the byte offset of the resulting data may not
883 be the same as the string offset.
885 Note that it is unsafe to use `fs.write` multiple times on the same file
886 without waiting for the callback. For this scenario,
887 `fs.createWriteStream` is strongly recommended.
889 On Linux, positional writes don't work when the file is opened in append mode.
890 The kernel ignores the position argument and always appends the data to
893 ## fs.writeFile(file, data[, options], callback)
895 * `file` {String | Integer} filename or file descriptor
896 * `data` {String | Buffer}
897 * `options` {Object | String}
898 * `encoding` {String | Null} default = `'utf8'`
899 * `mode` {Number} default = `0o666`
900 * `flag` {String} default = `'w'`
901 * `callback` {Function}
903 Asynchronously writes data to a file, replacing the file if it already exists.
904 `data` can be a string or a buffer.
906 The `encoding` option is ignored if `data` is a buffer. It defaults
911 fs.writeFile('message.txt', 'Hello Node.js', (err) => {
913 console.log('It\'s saved!');
916 If `options` is a string, then it specifies the encoding. Example:
918 fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
920 Any specified file descriptor has to support writing.
922 Note that it is unsafe to use `fs.writeFile` multiple times on the same file
923 without waiting for the callback. For this scenario,
924 `fs.createWriteStream` is strongly recommended.
926 _Note: Specified file descriptors will not be closed automatically._
928 ## fs.writeFileSync(file, data[, options])
930 The synchronous version of [`fs.writeFile()`][]. Returns `undefined`.
932 ## fs.writeSync(fd, buffer, offset, length[, position])
934 ## fs.writeSync(fd, data[, position[, encoding]])
936 Synchronous versions of [`fs.write()`][]. Returns the number of bytes written.
938 [`Buffer.byteLength`]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding
939 [`Buffer`]: buffer.html#buffer_buffer
940 [Caveats]: #fs_caveats
941 [`fs.access()`]: #fs_fs_access_path_mode_callback
942 [`fs.accessSync()`]: #fs_fs_accesssync_path_mode
943 [`fs.appendFile()`]: fs.html#fs_fs_appendfile_file_data_options_callback
944 [`fs.exists()`]: fs.html#fs_fs_exists_path_callback
945 [`fs.fstat()`]: #fs_fs_fstat_fd_callback
946 [`fs.FSWatcher`]: #fs_class_fs_fswatcher
947 [`fs.futimes()`]: #fs_fs_futimes_fd_atime_mtime_callback
948 [`fs.lstat()`]: #fs_fs_lstat_path_callback
949 [`fs.open()`]: #fs_fs_open_path_flags_mode_callback
950 [`fs.read()`]: #fs_fs_read_fd_buffer_offset_length_position_callback
951 [`fs.readFile`]: #fs_fs_readfile_file_options_callback
952 [`fs.stat()`]: #fs_fs_stat_path_callback
953 [`fs.Stats`]: #fs_class_fs_stats
954 [`fs.statSync()`]: #fs_fs_statsync_path
955 [`fs.utimes()`]: #fs_fs_futimes_fd_atime_mtime_callback
956 [`fs.watch()`]: #fs_fs_watch_filename_options_listener
957 [`fs.write()`]: #fs_fs_write_fd_buffer_offset_length_position_callback
958 [`fs.writeFile()`]: #fs_fs_writefile_file_data_options_callback
959 [`net.Socket`]: net.html#net_class_net_socket
960 [`ReadStream`]: #fs_class_fs_readstream
961 [`stat()`]: fs.html#fs_fs_stat_path_callback
962 [`util.inspect(stats)`]: util.html#util_util_inspect_object_options
963 [`WriteStream`]: #fs_class_fs_writestream
964 [MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
965 [MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
966 [Readable Stream]: stream.html#stream_class_stream_readable
967 [Writable Stream]: stream.html#stream_class_stream_writable