doc: remove "above" and "below" references
[platform/upstream/nodejs.git] / doc / api / fs.markdown
1 # File System
2
3     Stability: 2 - Stable
4
5 <!--name=fs-->
6
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
9 synchronous forms.
10
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`.
15
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.
18
19 Here is an example of the asynchronous version:
20
21     const fs = require('fs');
22
23     fs.unlink('/tmp/hello', (err) => {
24       if (err) throw err;
25       console.log('successfully deleted /tmp/hello');
26     });
27
28 Here is the synchronous version:
29
30     const fs = require('fs');
31
32     fs.unlinkSync('/tmp/hello');
33     console.log('successfully deleted /tmp/hello');
34
35 With the asynchronous methods there is no guaranteed ordering. So the
36 following is prone to error:
37
38     fs.rename('/tmp/hello', '/tmp/world', (err) => {
39       if (err) throw err;
40       console.log('renamed complete');
41     });
42     fs.stat('/tmp/world', (err, stats) => {
43       if (err) throw err;
44       console.log(`stats: ${JSON.stringify(stats)}`);
45     });
46
47 It could be that `fs.stat` is executed before `fs.rename`.
48 The correct way to do this is to chain the callbacks.
49
50     fs.rename('/tmp/hello', '/tmp/world', (err) => {
51       if (err) throw err;
52       fs.stat('/tmp/world', (err, stats) => {
53         if (err) throw err;
54         console.log(`stats: ${JSON.stringify(stats)}`);
55       });
56     });
57
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.
61
62 The relative path to a filename can be used. Remember, however, that this path
63 will be relative to `process.cwd()`.
64
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:
68
69     $ cat script.js
70     function bad() {
71       require('fs').readFile('/');
72     }
73     bad();
74
75     $ env NODE_DEBUG=fs node script.js
76     fs.js:66
77             throw err;
78                   ^
79     Error: EISDIR, read
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)
85         <etc.>
86
87 ## Class: fs.FSWatcher
88
89 Objects returned from `fs.watch()` are of this type.
90
91 ### Event: 'change'
92
93 * `event` {String} The type of fs change
94 * `filename` {String} The filename that changed (if relevant/available)
95
96 Emitted when something changes in a watched directory or file.
97 See more details in [`fs.watch()`][].
98
99 ### Event: 'error'
100
101 * `error` {Error object}
102
103 Emitted when an error occurs.
104
105 ### watcher.close()
106
107 Stop watching for changes on the given `fs.FSWatcher`.
108
109 ## Class: fs.ReadStream
110
111 `ReadStream` is a [Readable Stream][].
112
113 ### Event: 'open'
114
115 * `fd` {Integer} file descriptor used by the ReadStream.
116
117 Emitted when the ReadStream's file is opened.
118
119 ### readStream.path
120
121 The path to the file the stream is reading from.
122
123 ## Class: fs.Stats
124
125 Objects returned from [`fs.stat()`][], [`fs.lstat()`][] and [`fs.fstat()`][] and their
126 synchronous counterparts are of this type.
127
128  - `stats.isFile()`
129  - `stats.isDirectory()`
130  - `stats.isBlockDevice()`
131  - `stats.isCharacterDevice()`
132  - `stats.isSymbolicLink()` (only valid with [`fs.lstat()`][])
133  - `stats.isFIFO()`
134  - `stats.isSocket()`
135
136 For a regular file [`util.inspect(stats)`][] would return a string very
137 similar to this:
138
139     { dev: 2114,
140       ino: 48064969,
141       mode: 33188,
142       nlink: 1,
143       uid: 85,
144       gid: 100,
145       rdev: 0,
146       size: 527,
147       blksize: 4096,
148       blocks: 8,
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 }
153
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]
162 page.
163
164 ### Stat Time Values
165
166 The times in the stat object have the following semantics:
167
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)`
182   system call.
183
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.
187
188 ## Class: fs.WriteStream
189
190 `WriteStream` is a [Writable Stream][].
191
192 ### Event: 'open'
193
194 * `fd` {Integer} file descriptor used by the WriteStream.
195
196 Emitted when the WriteStream's file is opened.
197
198 ### writeStream.bytesWritten
199
200 The number of bytes written so far. Does not include data that is still queued
201 for writing.
202
203 ### writeStream.path
204
205 The path to the file the stream is writing to.
206
207 ## fs.access(path[, mode], callback)
208
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.
213
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`).
221
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.
226
227     fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) {
228       console.log(err ? 'no access!' : 'can read/write');
229     });
230
231 ## fs.accessSync(path[, mode])
232
233 Synchronous version of [`fs.access()`][]. This throws if any accessibility checks
234 fail, and does nothing otherwise.
235
236 ## fs.appendFile(file, data[, options], callback)
237
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}
245
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.
248
249 Example:
250
251     fs.appendFile('message.txt', 'data to append', (err) => {
252       if (err) throw err;
253       console.log('The "data to append" was appended to file!');
254     });
255
256 If `options` is a string, then it specifies the encoding. Example:
257
258     fs.appendFile('message.txt', 'data to append', 'utf8', callback);
259
260 Any specified file descriptor has to have been opened for appending.
261
262 _Note: Specified file descriptors will not be closed automatically._
263
264 ## fs.appendFileSync(file, data[, options])
265
266 The synchronous version of [`fs.appendFile()`][]. Returns `undefined`.
267
268 ## fs.chmod(path, mode, callback)
269
270 Asynchronous chmod(2). No arguments other than a possible exception are given
271 to the completion callback.
272
273 ## fs.chmodSync(path, mode)
274
275 Synchronous chmod(2). Returns `undefined`.
276
277 ## fs.chown(path, uid, gid, callback)
278
279 Asynchronous chown(2). No arguments other than a possible exception are given
280 to the completion callback.
281
282 ## fs.chownSync(path, uid, gid)
283
284 Synchronous chown(2). Returns `undefined`.
285
286 ## fs.close(fd, callback)
287
288 Asynchronous close(2).  No arguments other than a possible exception are given
289 to the completion callback.
290
291 ## fs.closeSync(fd)
292
293 Synchronous close(2). Returns `undefined`.
294
295 ## fs.createReadStream(path[, options])
296
297 Returns a new [`ReadStream`][] object. (See [Readable Stream][]).
298
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.
302
303 `options` is an object or string with the following defaults:
304
305     { flags: 'r',
306       encoding: null,
307       fd: null,
308       mode: 0o666,
309       autoClose: true
310     }
311
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`][].
315
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
319 [`net.Socket`][].
320
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
325 automatically.
326
327 `mode` sets the file mode (permission and sticky bits), but only if the
328 file was created.
329
330 An example to read the last 10 bytes of a file which is 100 bytes long:
331
332     fs.createReadStream('sample.txt', {start: 90, end: 99});
333
334 If `options` is a string, then it specifies the encoding.
335
336 ## fs.createWriteStream(path[, options])
337
338 Returns a new [`WriteStream`][] object. (See [Writable Stream][]).
339
340 `options` is an object or string with the following defaults:
341
342     { flags: 'w',
343       defaultEncoding: 'utf8',
344       fd: null,
345       mode: 0o666 }
346
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`][].
351
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`][].
356
357 If `options` is a string, then it specifies the encoding.
358
359 ## fs.exists(path, callback)
360
361     Stability: 0 - Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.
362
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:
365
366     fs.exists('/etc/passwd', (exists) => {
367       console.log(exists ? 'it\'s there' : 'no passwd!');
368     });
369
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
374 non-existent.
375
376 ## fs.existsSync(path)
377
378     Stability: 0 - Deprecated: Use [`fs.statSync()`][] or [`fs.accessSync()`][] instead.
379
380 Synchronous version of [`fs.exists()`][].
381 Returns `true` if the file exists, `false` otherwise.
382
383 ## fs.fchmod(fd, mode, callback)
384
385 Asynchronous fchmod(2). No arguments other than a possible exception
386 are given to the completion callback.
387
388 ## fs.fchmodSync(fd, mode)
389
390 Synchronous fchmod(2). Returns `undefined`.
391
392 ## fs.fchown(fd, uid, gid, callback)
393
394 Asynchronous fchown(2). No arguments other than a possible exception are given
395 to the completion callback.
396
397 ## fs.fchownSync(fd, uid, gid)
398
399 Synchronous fchown(2). Returns `undefined`.
400
401 ## fs.fstat(fd, callback)
402
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`.
406
407 ## fs.fstatSync(fd)
408
409 Synchronous fstat(2). Returns an instance of `fs.Stats`.
410
411 ## fs.fsync(fd, callback)
412
413 Asynchronous fsync(2). No arguments other than a possible exception are given
414 to the completion callback.
415
416 ## fs.fsyncSync(fd)
417
418 Synchronous fsync(2). Returns `undefined`.
419
420 ## fs.ftruncate(fd, len, callback)
421
422 Asynchronous ftruncate(2). No arguments other than a possible exception are
423 given to the completion callback.
424
425 ## fs.ftruncateSync(fd, len)
426
427 Synchronous ftruncate(2). Returns `undefined`.
428
429 ## fs.futimes(fd, atime, mtime, callback)
430
431 Change the file timestamps of a file referenced by the supplied file
432 descriptor.
433
434 ## fs.futimesSync(fd, atime, mtime)
435
436 Synchronous version of [`fs.futimes()`][]. Returns `undefined`.
437
438 ## fs.lchmod(path, mode, callback)
439
440 Asynchronous lchmod(2). No arguments other than a possible exception
441 are given to the completion callback.
442
443 Only available on Mac OS X.
444
445 ## fs.lchmodSync(path, mode)
446
447 Synchronous lchmod(2). Returns `undefined`.
448
449 ## fs.lchown(path, uid, gid, callback)
450
451 Asynchronous lchown(2). No arguments other than a possible exception are given
452 to the completion callback.
453
454 ## fs.lchownSync(path, uid, gid)
455
456 Synchronous lchown(2). Returns `undefined`.
457
458 ## fs.link(srcpath, dstpath, callback)
459
460 Asynchronous link(2). No arguments other than a possible exception are given to
461 the completion callback.
462
463 ## fs.linkSync(srcpath, dstpath)
464
465 Synchronous link(2). Returns `undefined`.
466
467 ## fs.lstat(path, callback)
468
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
472 refers to.
473
474 ## fs.lstatSync(path)
475
476 Synchronous lstat(2). Returns an instance of `fs.Stats`.
477
478 ## fs.mkdir(path[, mode], callback)
479
480 Asynchronous mkdir(2). No arguments other than a possible exception are given
481 to the completion callback. `mode` defaults to `0o777`.
482
483 ## fs.mkdirSync(path[, mode])
484
485 Synchronous mkdir(2). Returns `undefined`.
486
487 ## fs.open(path, flags[, mode], callback)
488
489 Asynchronous file open. See open(2). `flags` can be:
490
491 * `'r'` - Open file for reading.
492 An exception occurs if the file does not exist.
493
494 * `'r+'` - Open file for reading and writing.
495 An exception occurs if the file does not exist.
496
497 * `'rs'` - Open file for reading in synchronous mode. Instructs the operating
498   system to bypass the local file system cache.
499
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.
503
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()`
506
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.
509
510 * `'w'` - Open file for writing.
511 The file is created (if it does not exist) or truncated (if it exists).
512
513 * `'wx'` - Like `'w'` but fails if `path` exists.
514
515 * `'w+'` - Open file for reading and writing.
516 The file is created (if it does not exist) or truncated (if it exists).
517
518 * `'wx+'` - Like `'w+'` but fails if `path` exists.
519
520 * `'a'` - Open file for appending.
521 The file is created if it does not exist.
522
523 * `'ax'` - Like `'a'` but fails if `path` exists.
524
525 * `'a+'` - Open file for reading and appending.
526 The file is created if it does not exist.
527
528 * `'ax+'` - Like `'a+'` but fails if `path` exists.
529
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.
532
533 The callback gets two arguments `(err, fd)`.
534
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
538 systems.
539
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.
544
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
547 the end of the file.
548
549 ## fs.openSync(path, flags[, mode])
550
551 Synchronous version of [`fs.open()`][]. Returns an integer representing the file
552 descriptor.
553
554 ## fs.read(fd, buffer, offset, length, position, callback)
555
556 Read data from the file specified by `fd`.
557
558 `buffer` is the buffer that the data will be written to.
559
560 `offset` is the offset in the buffer to start writing at.
561
562 `length` is an integer specifying the number of bytes to read.
563
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.
566
567 The callback is given the three arguments, `(err, bytesRead, buffer)`.
568
569 ## fs.readdir(path, callback)
570
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 `'..'`.
574
575 ## fs.readdirSync(path)
576
577 Synchronous readdir(3). Returns an array of filenames excluding `'.'` and
578 `'..'`.
579
580 ## fs.readFile(file[, options], callback)
581
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}
587
588 Asynchronously reads the entire contents of a file. Example:
589
590     fs.readFile('/etc/passwd', (err, data) => {
591       if (err) throw err;
592       console.log(data);
593     });
594
595 The callback is passed two arguments `(err, data)`, where `data` is the
596 contents of the file.
597
598 If no encoding is specified, then the raw buffer is returned.
599
600 If `options` is a string, then it specifies the encoding. Example:
601
602     fs.readFile('/etc/passwd', 'utf8', callback);
603
604 Any specified file descriptor has to support reading.
605
606 _Note: Specified file descriptors will not be closed automatically._
607
608 ## fs.readFileSync(file[, options])
609
610 Synchronous version of [`fs.readFile`][]. Returns the contents of the `file`.
611
612 If the `encoding` option is specified then this function returns a
613 string. Otherwise it returns a buffer.
614
615 ## fs.readlink(path, callback)
616
617 Asynchronous readlink(2). The callback gets two arguments `(err,
618 linkString)`.
619
620 ## fs.readlinkSync(path)
621
622 Synchronous readlink(2). Returns the symbolic link's string value.
623
624 ## fs.realpath(path[, cache], callback)
625
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.
630
631 Example:
632
633     var cache = {'/etc':'/private/etc'};
634     fs.realpath('/etc/passwd', cache, (err, resolvedPath) => {
635       if (err) throw err;
636       console.log(resolvedPath);
637     });
638
639 ## fs.readSync(fd, buffer, offset, length, position)
640
641 Synchronous version of [`fs.read()`][]. Returns the number of `bytesRead`.
642
643 ## fs.realpathSync(path[, cache])
644
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.
648
649 ## fs.rename(oldPath, newPath, callback)
650
651 Asynchronous rename(2). No arguments other than a possible exception are given
652 to the completion callback.
653
654 ## fs.renameSync(oldPath, newPath)
655
656 Synchronous rename(2). Returns `undefined`.
657
658 ## fs.rmdir(path, callback)
659
660 Asynchronous rmdir(2). No arguments other than a possible exception are given
661 to the completion callback.
662
663 ## fs.rmdirSync(path)
664
665 Synchronous rmdir(2). Returns `undefined`.
666
667 ## fs.stat(path, callback)
668
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
671 information.
672
673 ## fs.statSync(path)
674
675 Synchronous stat(2). Returns an instance of [`fs.Stats`][].
676
677 ## fs.symlink(target, path[, type], callback)
678
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.
685
686 Here is an example below:
687
688     fs.symlink('./foo', './new-port');
689
690 It would create a symlic link named with "new-port" that points to "foo".
691
692 ## fs.symlinkSync(target, path[, type])
693
694 Synchronous symlink(2). Returns `undefined`.
695
696 ## fs.truncate(path, len, callback)
697
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.
701
702 ## fs.truncateSync(path, len)
703
704 Synchronous truncate(2). Returns `undefined`.
705
706 ## fs.unlink(path, callback)
707
708 Asynchronous unlink(2). No arguments other than a possible exception are given
709 to the completion callback.
710
711 ## fs.unlinkSync(path)
712
713 Synchronous unlink(2). Returns `undefined`.
714
715 ## fs.unwatchFile(filename[, listener])
716
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`.
720
721 Calling `fs.unwatchFile()` with a filename that is not being watched is a
722 no-op, not an error.
723
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()`
726 when possible._
727
728 ## fs.utimes(path, atime, mtime, callback)
729
730 Change file timestamps of the file referenced by the supplied path.
731
732 Note: the arguments `atime` and `mtime` of the following related functions does
733 follow the below rules:
734
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
738   `Date.now()`.
739
740 ## fs.utimesSync(path, atime, mtime)
741
742 Synchronous version of [`fs.utimes()`][]. Returns `undefined`.
743
744 ## fs.watch(filename[, options][, listener])
745
746 Watch for changes on `filename`, where `filename` is either a file or a
747 directory.  The returned object is a [`fs.FSWatcher`][].
748
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][]).
755
756 The default is `{ persistent: true, recursive: false }`.
757
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
760 the event.
761
762 ### Caveats
763
764 <!--type=misc-->
765
766 The `fs.watch` API is not 100% consistent across platforms, and is
767 unavailable in some situations.
768
769 The recursive option is only supported on OS X and Windows.
770
771 #### Availability
772
773 <!--type=misc-->
774
775 This feature depends on the underlying operating system providing a way
776 to be notified of filesystem changes.
777
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`.
783
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
787 reliably or at all.
788
789 You can still use `fs.watchFile`, which uses stat polling, but it is slower and
790 less reliable.
791
792 #### Filename Argument
793
794 <!--type=misc-->
795
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.
800
801     fs.watch('somedir', (event, filename) => {
802       console.log(`event is: ${event}`);
803       if (filename) {
804         console.log(`filename provided: ${filename}`);
805       } else {
806         console.log('filename not provided');
807       }
808     });
809
810 ## fs.watchFile(filename[, options], listener)
811
812 Watch for changes on `filename`. The callback `listener` will be called each
813 time the file is accessed.
814
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 }`.
821
822 The `listener` gets two arguments the current stat object and the previous
823 stat object:
824
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}`);
828     });
829
830 These stat objects are instances of `fs.Stat`.
831
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`.
834
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._
840
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`
843 when possible._
844
845 ## fs.write(fd, buffer, offset, length[, position], callback)
846
847 Write `buffer` to the file specified by `fd`.
848
849 `offset` and `length` determine the part of the buffer to be written.
850
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).
854
855 The callback will be given three arguments `(err, written, buffer)` where
856 `written` specifies how many _bytes_ were written from `buffer`.
857
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.
861
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
864 the end of the file.
865
866 ## fs.write(fd, data[, position[, encoding]], callback)
867
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.
870
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).
874
875 `encoding` is the expected string encoding.
876
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`][].
880
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.
884
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.
888
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
891 the end of the file.
892
893 ## fs.writeFile(file, data[, options], callback)
894
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}
902
903 Asynchronously writes data to a file, replacing the file if it already exists.
904 `data` can be a string or a buffer.
905
906 The `encoding` option is ignored if `data` is a buffer. It defaults
907 to `'utf8'`.
908
909 Example:
910
911     fs.writeFile('message.txt', 'Hello Node.js', (err) => {
912       if (err) throw err;
913       console.log('It\'s saved!');
914     });
915
916 If `options` is a string, then it specifies the encoding. Example:
917
918     fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
919
920 Any specified file descriptor has to support writing.
921
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.
925
926 _Note: Specified file descriptors will not be closed automatically._
927
928 ## fs.writeFileSync(file, data[, options])
929
930 The synchronous version of [`fs.writeFile()`][]. Returns `undefined`.
931
932 ## fs.writeSync(fd, buffer, offset, length[, position])
933
934 ## fs.writeSync(fd, data[, position[, encoding]])
935
936 Synchronous versions of [`fs.write()`][]. Returns the number of bytes written.
937
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