0692d697e258a67d8ab9f6eb2c4d287bc38d5ab7
[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     var fs = require('fs');
22
23     fs.unlink('/tmp/hello', function (err) {
24       if (err) throw err;
25       console.log('successfully deleted /tmp/hello');
26     });
27
28 Here is the synchronous version:
29
30     var 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', function (err) {
39       if (err) throw err;
40       console.log('renamed complete');
41     });
42     fs.stat('/tmp/world', function (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', function (err) {
51       if (err) throw err;
52       fs.stat('/tmp/world', function (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](#fs_fs_watch_filename_options_listener).
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](stream.html#stream_class_stream_readable).
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 ## Class: fs.Stats
120
121 Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their
122 synchronous counterparts are of this type.
123
124  - `stats.isFile()`
125  - `stats.isDirectory()`
126  - `stats.isBlockDevice()`
127  - `stats.isCharacterDevice()`
128  - `stats.isSymbolicLink()` (only valid with  `fs.lstat()`)
129  - `stats.isFIFO()`
130  - `stats.isSocket()`
131
132 For a regular file `util.inspect(stats)` would return a string very
133 similar to this:
134
135     { dev: 2114,
136       ino: 48064969,
137       mode: 33188,
138       nlink: 1,
139       uid: 85,
140       gid: 100,
141       rdev: 0,
142       size: 527,
143       blksize: 4096,
144       blocks: 8,
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 }
149
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]
158 page.
159
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
162
163 ### Stat Time Values
164
165 The times in the stat object have the following semantics:
166
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)`
181   system call.
182
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.
186
187 ## Class: fs.WriteStream
188
189 `WriteStream` is a [Writable Stream](stream.html#stream_class_stream_writable).
190
191 ### Event: 'open'
192
193 * `fd` {Integer} file descriptor used by the WriteStream.
194
195 Emitted when the WriteStream's file is opened.
196
197 ### writeStream.bytesWritten
198
199 The number of bytes written so far. Does not include data that is still queued
200 for writing.
201
202 ## fs.access(path[, mode], callback)
203
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.
208
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`).
216
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.
221
222     fs.access('/etc/passwd', fs.R_OK | fs.W_OK, function (err) {
223       console.log(err ? 'no access!' : 'can read/write');
224     });
225
226 ## fs.accessSync(path[, mode])
227
228 Synchronous version of `fs.access`. This throws if any accessibility checks
229 fail, and does nothing otherwise.
230
231 ## fs.appendFile(file, data[, options], callback)
232
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}
240
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.
243
244 Example:
245
246     fs.appendFile('message.txt', 'data to append', function (err) {
247       if (err) throw err;
248       console.log('The "data to append" was appended to file!');
249     });
250
251 If `options` is a string, then it specifies the encoding. Example:
252
253     fs.appendFile('message.txt', 'data to append', 'utf8', callback);
254
255 Any specified file descriptor has to have been opened for appending.
256
257 _Note: Specified file descriptors will not be closed automatically._
258
259 ## fs.appendFileSync(file, data[, options])
260
261 The synchronous version of `fs.appendFile`. Returns `undefined`.
262
263 ## fs.chmod(path, mode, callback)
264
265 Asynchronous chmod(2). No arguments other than a possible exception are given
266 to the completion callback.
267
268 ## fs.chmodSync(path, mode)
269
270 Synchronous chmod(2). Returns `undefined`.
271
272 ## fs.chown(path, uid, gid, callback)
273
274 Asynchronous chown(2). No arguments other than a possible exception are given
275 to the completion callback.
276
277 ## fs.chownSync(path, uid, gid)
278
279 Synchronous chown(2). Returns `undefined`.
280
281 ## fs.close(fd, callback)
282
283 Asynchronous close(2).  No arguments other than a possible exception are given
284 to the completion callback.
285
286 ## fs.closeSync(fd)
287
288 Synchronous close(2). Returns `undefined`.
289
290 ## fs.createReadStream(path[, options])
291
292 Returns a new ReadStream object (See `Readable Stream`).
293
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.
297
298 `options` is an object or string with the following defaults:
299
300     { flags: 'r',
301       encoding: null,
302       fd: null,
303       mode: 0o666,
304       autoClose: true
305     }
306
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][].
310
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.
313
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
318 automatically.
319
320 `mode` sets the file mode (permission and sticky bits), but only if the
321 file was created.
322
323 An example to read the last 10 bytes of a file which is 100 bytes long:
324
325     fs.createReadStream('sample.txt', {start: 90, end: 99});
326
327 If `options` is a string, then it specifies the encoding.
328
329 ## fs.createWriteStream(path[, options])
330
331 Returns a new WriteStream object (See `Writable Stream`).
332
333 `options` is an object or string with the following defaults:
334
335     { flags: 'w',
336       defaultEncoding: 'utf8',
337       fd: null,
338       mode: 0o666 }
339
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][].
344
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.
348
349 If `options` is a string, then it specifies the encoding.
350
351 ## fs.exists(path, callback)
352
353     Stability: 0 - Deprecated: Use [fs.stat][] or [fs.access][] instead.
354
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:
357
358     fs.exists('/etc/passwd', function (exists) {
359       console.log(exists ? "it's there" : 'no passwd!');
360     });
361
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
366 non-existent.
367
368 ## fs.existsSync(path)
369
370 Synchronous version of [`fs.exists`](fs.html#fs_fs_exists_path_callback).
371 Returns `true` if the file exists, `false` otherwise.
372
373     Stability: 0 - Deprecated: Use [fs.statSync][] or [fs.accessSync][] instead.
374
375 ## fs.fchmod(fd, mode, callback)
376
377 Asynchronous fchmod(2). No arguments other than a possible exception
378 are given to the completion callback.
379
380 ## fs.fchmodSync(fd, mode)
381
382 Synchronous fchmod(2). Returns `undefined`.
383
384 ## fs.fchown(fd, uid, gid, callback)
385
386 Asynchronous fchown(2). No arguments other than a possible exception are given
387 to the completion callback.
388
389 ## fs.fchownSync(fd, uid, gid)
390
391 Synchronous fchown(2). Returns `undefined`.
392
393 ## fs.fstat(fd, callback)
394
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`.
398
399 ## fs.fstatSync(fd)
400
401 Synchronous fstat(2). Returns an instance of `fs.Stats`.
402
403 ## fs.fsync(fd, callback)
404
405 Asynchronous fsync(2). No arguments other than a possible exception are given
406 to the completion callback.
407
408 ## fs.fsyncSync(fd)
409
410 Synchronous fsync(2). Returns `undefined`.
411
412 ## fs.ftruncate(fd, len, callback)
413
414 Asynchronous ftruncate(2). No arguments other than a possible exception are
415 given to the completion callback.
416
417 ## fs.ftruncateSync(fd, len)
418
419 Synchronous ftruncate(2). Returns `undefined`.
420
421 ## fs.futimes(fd, atime, mtime, callback)
422
423 Change the file timestamps of a file referenced by the supplied file
424 descriptor.
425
426 ## fs.futimesSync(fd, atime, mtime)
427
428 Synchronous version of `fs.futimes()`. Returns `undefined`.
429
430 ## fs.lchmod(path, mode, callback)
431
432 Asynchronous lchmod(2). No arguments other than a possible exception
433 are given to the completion callback.
434
435 Only available on Mac OS X.
436
437 ## fs.lchmodSync(path, mode)
438
439 Synchronous lchmod(2). Returns `undefined`.
440
441 ## fs.lchown(path, uid, gid, callback)
442
443 Asynchronous lchown(2). No arguments other than a possible exception are given
444 to the completion callback.
445
446 ## fs.lchownSync(path, uid, gid)
447
448 Synchronous lchown(2). Returns `undefined`.
449
450 ## fs.link(srcpath, dstpath, callback)
451
452 Asynchronous link(2). No arguments other than a possible exception are given to
453 the completion callback.
454
455 ## fs.linkSync(srcpath, dstpath)
456
457 Synchronous link(2). Returns `undefined`.
458
459 ## fs.lstat(path, callback)
460
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
464 refers to.
465
466 ## fs.lstatSync(path)
467
468 Synchronous lstat(2). Returns an instance of `fs.Stats`.
469
470 ## fs.mkdir(path[, mode], callback)
471
472 Asynchronous mkdir(2). No arguments other than a possible exception are given
473 to the completion callback. `mode` defaults to `0o777`.
474
475 ## fs.mkdirSync(path[, mode])
476
477 Synchronous mkdir(2). Returns `undefined`.
478
479 ## fs.open(path, flags[, mode], callback)
480
481 Asynchronous file open. See open(2). `flags` can be:
482
483 * `'r'` - Open file for reading.
484 An exception occurs if the file does not exist.
485
486 * `'r+'` - Open file for reading and writing.
487 An exception occurs if the file does not exist.
488
489 * `'rs'` - Open file for reading in synchronous mode. Instructs the operating
490   system to bypass the local file system cache.
491
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.
495
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()`
498
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.
501
502 * `'w'` - Open file for writing.
503 The file is created (if it does not exist) or truncated (if it exists).
504
505 * `'wx'` - Like `'w'` but fails if `path` exists.
506
507 * `'w+'` - Open file for reading and writing.
508 The file is created (if it does not exist) or truncated (if it exists).
509
510 * `'wx+'` - Like `'w+'` but fails if `path` exists.
511
512 * `'a'` - Open file for appending.
513 The file is created if it does not exist.
514
515 * `'ax'` - Like `'a'` but fails if `path` exists.
516
517 * `'a+'` - Open file for reading and appending.
518 The file is created if it does not exist.
519
520 * `'ax+'` - Like `'a+'` but fails if `path` exists.
521
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.
524
525 The callback gets two arguments `(err, fd)`.
526
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
530 systems.
531
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
534 the end of the file.
535
536 ## fs.openSync(path, flags[, mode])
537
538 Synchronous version of `fs.open()`. Returns an integer representing the file
539 descriptor.
540
541 ## fs.read(fd, buffer, offset, length, position, callback)
542
543 Read data from the file specified by `fd`.
544
545 `buffer` is the buffer that the data will be written to.
546
547 `offset` is the offset in the buffer to start writing at.
548
549 `length` is an integer specifying the number of bytes to read.
550
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.
553
554 The callback is given the three arguments, `(err, bytesRead, buffer)`.
555
556 ## fs.readdir(path, callback)
557
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 `'..'`.
561
562 ## fs.readdirSync(path)
563
564 Synchronous readdir(3). Returns an array of filenames excluding `'.'` and
565 `'..'`.
566
567 ## fs.readFile(file[, options], callback)
568
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}
574
575 Asynchronously reads the entire contents of a file. Example:
576
577     fs.readFile('/etc/passwd', function (err, data) {
578       if (err) throw err;
579       console.log(data);
580     });
581
582 The callback is passed two arguments `(err, data)`, where `data` is the
583 contents of the file.
584
585 If no encoding is specified, then the raw buffer is returned.
586
587 If `options` is a string, then it specifies the encoding. Example:
588
589     fs.readFile('/etc/passwd', 'utf8', callback);
590
591 Any specified file descriptor has to support reading.
592
593 _Note: Specified file descriptors will not be closed automatically._
594
595 ## fs.readFileSync(file[, options])
596
597 Synchronous version of `fs.readFile`. Returns the contents of the `file`.
598
599 If the `encoding` option is specified then this function returns a
600 string. Otherwise it returns a buffer.
601
602 ## fs.readlink(path, callback)
603
604 Asynchronous readlink(2). The callback gets two arguments `(err,
605 linkString)`.
606
607 ## fs.readlinkSync(path)
608
609 Synchronous readlink(2). Returns the symbolic link's string value.
610
611 ## fs.realpath(path[, cache], callback)
612
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.
617
618 Example:
619
620     var cache = {'/etc':'/private/etc'};
621     fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
622       if (err) throw err;
623       console.log(resolvedPath);
624     });
625
626 ## fs.readSync(fd, buffer, offset, length, position)
627
628 Synchronous version of `fs.read`. Returns the number of `bytesRead`.
629
630 ## fs.realpathSync(path[, cache])
631
632 Synchronous realpath(2). Returns the resolved path.
633
634 ## fs.rename(oldPath, newPath, callback)
635
636 Asynchronous rename(2). No arguments other than a possible exception are given
637 to the completion callback.
638
639 ## fs.renameSync(oldPath, newPath)
640
641 Synchronous rename(2). Returns `undefined`.
642
643 ## fs.rmdir(path, callback)
644
645 Asynchronous rmdir(2). No arguments other than a possible exception are given
646 to the completion callback.
647
648 ## fs.rmdirSync(path)
649
650 Synchronous rmdir(2). Returns `undefined`.
651
652 ## fs.stat(path, callback)
653
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.
657
658 ## fs.statSync(path)
659
660 Synchronous stat(2). Returns an instance of `fs.Stats`.
661
662 ## fs.symlink(destination, path[, type], callback)
663
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.
670
671 ## fs.symlinkSync(destination, path[, type])
672
673 Synchronous symlink(2). Returns `undefined`.
674
675 ## fs.truncate(path, len, callback)
676
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.
680
681 ## fs.truncateSync(path, len)
682
683 Synchronous truncate(2). Returns `undefined`.
684
685 ## fs.unlink(path, callback)
686
687 Asynchronous unlink(2). No arguments other than a possible exception are given
688 to the completion callback.
689
690 ## fs.unlinkSync(path)
691
692 Synchronous unlink(2). Returns `undefined`.
693
694 ## fs.unwatchFile(filename[, listener])
695
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`.
699
700 Calling `fs.unwatchFile()` with a filename that is not being watched is a
701 no-op, not an error.
702
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`
705 when possible._
706
707 ## fs.utimes(path, atime, mtime, callback)
708
709 Change file timestamps of the file referenced by the supplied path.
710
711 Note: the arguments `atime` and `mtime` of the following related functions does
712 follow the below rules:
713
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
717   `Date.now()`.
718
719 ## fs.utimesSync(path, atime, mtime)
720
721 Synchronous version of `fs.utimes()`. Returns `undefined`.
722
723 ## fs.watch(filename[, options][, listener])
724
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).
727
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).
734
735 The default is `{ persistent: true, recursive: false }`.
736
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
739 the event.
740
741 ### Caveats
742
743 <!--type=misc-->
744
745 The `fs.watch` API is not 100% consistent across platforms, and is
746 unavailable in some situations.
747
748 The recursive option is only supported on OS X and Windows.
749
750 #### Availability
751
752 <!--type=misc-->
753
754 This feature depends on the underlying operating system providing a way
755 to be notified of filesystem changes.
756
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`.
762
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
766 reliably or at all.
767
768 You can still use `fs.watchFile`, which uses stat polling, but it is slower and
769 less reliable.
770
771 #### Filename Argument
772
773 <!--type=misc-->
774
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.
779
780     fs.watch('somedir', function (event, filename) {
781       console.log('event is: ' + event);
782       if (filename) {
783         console.log('filename provided: ' + filename);
784       } else {
785         console.log('filename not provided');
786       }
787     });
788
789 ## fs.watchFile(filename[, options], listener)
790
791 Watch for changes on `filename`. The callback `listener` will be called each
792 time the file is accessed.
793
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 }`.
800
801 The `listener` gets two arguments the current stat object and the previous
802 stat object:
803
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);
807     });
808
809 These stat objects are instances of `fs.Stat`.
810
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`.
813
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._
819
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`
822 when possible._
823
824 ## fs.write(fd, buffer, offset, length[, position], callback)
825
826 Write `buffer` to the file specified by `fd`.
827
828 `offset` and `length` determine the part of the buffer to be written.
829
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).
833
834 The callback will be given three arguments `(err, written, buffer)` where
835 `written` specifies how many _bytes_ were written from `buffer`.
836
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.
840
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
843 the end of the file.
844
845 ## fs.write(fd, data[, position[, encoding]], callback)
846
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.
849
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).
853
854 `encoding` is the expected string encoding.
855
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).
860
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.
864
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.
868
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
871 the end of the file.
872
873 ## fs.writeFile(file, data[, options], callback)
874
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}
882
883 Asynchronously writes data to a file, replacing the file if it already exists.
884 `data` can be a string or a buffer.
885
886 The `encoding` option is ignored if `data` is a buffer. It defaults
887 to `'utf8'`.
888
889 Example:
890
891     fs.writeFile('message.txt', 'Hello Node.js', function (err) {
892       if (err) throw err;
893       console.log('It\'s saved!');
894     });
895
896 If `options` is a string, then it specifies the encoding. Example:
897
898     fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
899
900 Any specified file descriptor has to support writing.
901
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.
905
906 _Note: Specified file descriptors will not be closed automatically._
907
908 ## fs.writeFileSync(file, data[, options])
909
910 The synchronous version of `fs.writeFile`. Returns `undefined`.
911
912 ## fs.writeSync(fd, buffer, offset, length[, position])
913
914 ## fs.writeSync(fd, data[, position[, encoding]])
915
916 Synchronous versions of `fs.write()`. Returns the number of bytes written.
917
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