Merge branch 'v0.10'
[platform/upstream/nodejs.git] / doc / api / fs.markdown
1 # File System
2
3     Stability: 3 - 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 take a completion callback as its last argument.
12 The arguments passed to the completion callback depend on the method, but the
13 first argument is always reserved for an exception. If the operation was
14 completed successfully, then the first argument will be `null` or `undefined`.
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 Relative path to filename can be used, remember however that this path will be
63 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
88 ## fs.rename(oldPath, newPath, callback)
89
90 Asynchronous rename(2). No arguments other than a possible exception are given
91 to the completion callback.
92
93 ## fs.renameSync(oldPath, newPath)
94
95 Synchronous rename(2).
96
97 ## fs.ftruncate(fd, len, callback)
98
99 Asynchronous ftruncate(2). No arguments other than a possible exception are
100 given to the completion callback.
101
102 ## fs.ftruncateSync(fd, len)
103
104 Synchronous ftruncate(2).
105
106 ## fs.truncate(path, len, callback)
107
108 Asynchronous truncate(2). No arguments other than a possible exception are
109 given to the completion callback.
110
111 ## fs.truncateSync(path, len)
112
113 Synchronous truncate(2).
114
115 ## fs.chown(path, uid, gid, callback)
116
117 Asynchronous chown(2). No arguments other than a possible exception are given
118 to the completion callback.
119
120 ## fs.chownSync(path, uid, gid)
121
122 Synchronous chown(2).
123
124 ## fs.fchown(fd, uid, gid, callback)
125
126 Asynchronous fchown(2). No arguments other than a possible exception are given
127 to the completion callback.
128
129 ## fs.fchownSync(fd, uid, gid)
130
131 Synchronous fchown(2).
132
133 ## fs.lchown(path, uid, gid, callback)
134
135 Asynchronous lchown(2). No arguments other than a possible exception are given
136 to the completion callback.
137
138 ## fs.lchownSync(path, uid, gid)
139
140 Synchronous lchown(2).
141
142 ## fs.chmod(path, mode, callback)
143
144 Asynchronous chmod(2). No arguments other than a possible exception are given
145 to the completion callback.
146
147 ## fs.chmodSync(path, mode)
148
149 Synchronous chmod(2).
150
151 ## fs.fchmod(fd, mode, callback)
152
153 Asynchronous fchmod(2). No arguments other than a possible exception
154 are given to the completion callback.
155
156 ## fs.fchmodSync(fd, mode)
157
158 Synchronous fchmod(2).
159
160 ## fs.lchmod(path, mode, callback)
161
162 Asynchronous lchmod(2). No arguments other than a possible exception
163 are given to the completion callback.
164
165 Only available on Mac OS X.
166
167 ## fs.lchmodSync(path, mode)
168
169 Synchronous lchmod(2).
170
171 ## fs.stat(path, callback)
172
173 Asynchronous stat(2). The callback gets two arguments `(err, stats)` where
174 `stats` is a [fs.Stats](#fs_class_fs_stats) object.  See the [fs.Stats](#fs_class_fs_stats)
175 section below for more information.
176
177 ## fs.lstat(path, callback)
178
179 Asynchronous lstat(2). The callback gets two arguments `(err, stats)` where
180 `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if
181 `path` is a symbolic link, then the link itself is stat-ed, not the file that it
182 refers to.
183
184 ## fs.fstat(fd, callback)
185
186 Asynchronous fstat(2). The callback gets two arguments `(err, stats)` where
187 `stats` is a `fs.Stats` object. `fstat()` is identical to `stat()`, except that
188 the file to be stat-ed is specified by the file descriptor `fd`.
189
190 ## fs.statSync(path)
191
192 Synchronous stat(2). Returns an instance of `fs.Stats`.
193
194 ## fs.lstatSync(path)
195
196 Synchronous lstat(2). Returns an instance of `fs.Stats`.
197
198 ## fs.fstatSync(fd)
199
200 Synchronous fstat(2). Returns an instance of `fs.Stats`.
201
202 ## fs.link(srcpath, dstpath, callback)
203
204 Asynchronous link(2). No arguments other than a possible exception are given to
205 the completion callback.
206
207 ## fs.linkSync(srcpath, dstpath)
208
209 Synchronous link(2).
210
211 ## fs.symlink(srcpath, dstpath, [type], callback)
212
213 Asynchronous symlink(2). No arguments other than a possible exception are given
214 to the completion callback.
215 `type` argument can be either `'dir'`, `'file'`, or `'junction'` (default is `'file'`).  It is only 
216 used on Windows (ignored on other platforms).
217 Note that Windows junction points require the destination path to be absolute.  When using
218 `'junction'`, the `destination` argument will automatically be normalized to absolute path.
219
220 ## fs.symlinkSync(srcpath, dstpath, [type])
221
222 Synchronous symlink(2).
223
224 ## fs.readlink(path, callback)
225
226 Asynchronous readlink(2). The callback gets two arguments `(err,
227 linkString)`.
228
229 ## fs.readlinkSync(path)
230
231 Synchronous readlink(2). Returns the symbolic link's string value.
232
233 ## fs.realpath(path, [cache], callback)
234
235 Asynchronous realpath(2). The `callback` gets two arguments `(err,
236 resolvedPath)`. May use `process.cwd` to resolve relative paths. `cache` is an
237 object literal of mapped paths that can be used to force a specific path
238 resolution or avoid additional `fs.stat` calls for known real paths.
239
240 Example:
241
242     var cache = {'/etc':'/private/etc'};
243     fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
244       if (err) throw err;
245       console.log(resolvedPath);
246     });
247
248 ## fs.realpathSync(path, [cache])
249
250 Synchronous realpath(2). Returns the resolved path.
251
252 ## fs.unlink(path, callback)
253
254 Asynchronous unlink(2). No arguments other than a possible exception are given
255 to the completion callback.
256
257 ## fs.unlinkSync(path)
258
259 Synchronous unlink(2).
260
261 ## fs.rmdir(path, callback)
262
263 Asynchronous rmdir(2). No arguments other than a possible exception are given
264 to the completion callback.
265
266 ## fs.rmdirSync(path)
267
268 Synchronous rmdir(2).
269
270 ## fs.mkdir(path, [mode], callback)
271
272 Asynchronous mkdir(2). No arguments other than a possible exception are given
273 to the completion callback. `mode` defaults to `0777`.
274
275 ## fs.mkdirSync(path, [mode])
276
277 Synchronous mkdir(2).
278
279 ## fs.readdir(path, callback)
280
281 Asynchronous readdir(3).  Reads the contents of a directory.
282 The callback gets two arguments `(err, files)` where `files` is an array of
283 the names of the files in the directory excluding `'.'` and `'..'`.
284
285 ## fs.readdirSync(path)
286
287 Synchronous readdir(3). Returns an array of filenames excluding `'.'` and
288 `'..'`.
289
290 ## fs.close(fd, callback)
291
292 Asynchronous close(2).  No arguments other than a possible exception are given
293 to the completion callback.
294
295 ## fs.closeSync(fd)
296
297 Synchronous close(2).
298
299 ## fs.open(path, flags, [mode], callback)
300
301 Asynchronous file open. See open(2). `flags` can be:
302
303 * `'r'` - Open file for reading.
304 An exception occurs if the file does not exist.
305
306 * `'r+'` - Open file for reading and writing.
307 An exception occurs if the file does not exist.
308
309 * `'rs'` - Open file for reading in synchronous mode. Instructs the operating
310   system to bypass the local file system cache.
311
312   This is primarily useful for opening files on NFS mounts as it allows you to
313   skip the potentially stale local cache. It has a very real impact on I/O
314   performance so don't use this mode unless you need it.
315
316   Note that this doesn't turn `fs.open()` into a synchronous blocking call.
317   If that's what you want then you should be using `fs.openSync()`
318
319 * `'rs+'` - Open file for reading and writing, telling the OS to open it
320   synchronously. See notes for `'rs'` about using this with caution.
321
322 * `'w'` - Open file for writing.
323 The file is created (if it does not exist) or truncated (if it exists).
324
325 * `'wx'` - Like `'w'` but opens the file in exclusive mode.
326
327 * `'w+'` - Open file for reading and writing.
328 The file is created (if it does not exist) or truncated (if it exists).
329
330 * `'wx+'` - Like `'w+'` but opens the file in exclusive mode.
331
332 * `'a'` - Open file for appending.
333 The file is created if it does not exist.
334
335 * `'ax'` - Like `'a'` but opens the file in exclusive mode.
336
337 * `'a+'` - Open file for reading and appending.
338 The file is created if it does not exist.
339
340 * `'ax+'` - Like `'a+'` but opens the file in exclusive mode.
341
342 `mode` defaults to `0666`. The callback gets two arguments `(err, fd)`.
343
344 Exclusive mode (`O_EXCL`) ensures that `path` is newly created. `fs.open()`
345 fails if a file by that name already exists. On POSIX systems, symlinks are
346 not followed. Exclusive mode may or may not work with network file systems.
347
348 On Linux, positional writes don't work when the file is opened in append mode.
349 The kernel ignores the position argument and always appends the data to
350 the end of the file.
351
352 ## fs.openSync(path, flags, [mode])
353
354 Synchronous open(2).
355
356 ## fs.utimes(path, atime, mtime, callback)
357 ## fs.utimesSync(path, atime, mtime)
358
359 Change file timestamps of the file referenced by the supplied path.
360
361 ## fs.futimes(fd, atime, mtime, callback)
362 ## fs.futimesSync(fd, atime, mtime)
363
364 Change the file timestamps of a file referenced by the supplied file
365 descriptor.
366
367 ## fs.fsync(fd, callback)
368
369 Asynchronous fsync(2). No arguments other than a possible exception are given
370 to the completion callback.
371
372 ## fs.fsyncSync(fd)
373
374 Synchronous fsync(2).
375
376 ## fs.write(fd, buffer, offset, length, position, callback)
377
378 Write `buffer` to the file specified by `fd`.
379
380 `offset` and `length` determine the part of the buffer to be written.
381
382 `position` refers to the offset from the beginning of the file where this data
383 should be written. If `position` is `null`, the data will be written at the
384 current position.
385 See pwrite(2).
386
387 The callback will be given three arguments `(err, written, buffer)` where `written`
388 specifies how many _bytes_ were written from `buffer`.
389
390 Note that it is unsafe to use `fs.write` multiple times on the same file
391 without waiting for the callback. For this scenario,
392 `fs.createWriteStream` is strongly recommended.
393
394 On Linux, positional writes don't work when the file is opened in append mode.
395 The kernel ignores the position argument and always appends the data to
396 the end of the file.
397
398 ## fs.writeSync(fd, buffer, offset, length, position)
399
400 Synchronous version of `fs.write()`. Returns the number of bytes written.
401
402 ## fs.read(fd, buffer, offset, length, position, callback)
403
404 Read data from the file specified by `fd`.
405
406 `buffer` is the buffer that the data will be written to.
407
408 `offset` is offset within the buffer where reading will start.
409
410 `length` is an integer specifying the number of bytes to read.
411
412 `position` is an integer specifying where to begin reading from in the file.
413 If `position` is `null`, data will be read from the current file position.
414
415 The callback is given the three arguments, `(err, bytesRead, buffer)`.
416
417 ## fs.readSync(fd, buffer, offset, length, position)
418
419 Synchronous version of `fs.read`. Returns the number of `bytesRead`.
420
421 ## fs.readFile(filename, [options], callback)
422
423 * `filename` {String}
424 * `options` {Object}
425   * `encoding` {String | Null} default = `null`
426   * `flag` {String} default = `'r'`
427 * `callback` {Function}
428
429 Asynchronously reads the entire contents of a file. Example:
430
431     fs.readFile('/etc/passwd', function (err, data) {
432       if (err) throw err;
433       console.log(data);
434     });
435
436 The callback is passed two arguments `(err, data)`, where `data` is the
437 contents of the file.
438
439 If no encoding is specified, then the raw buffer is returned.
440
441
442 ## fs.readFileSync(filename, [options])
443
444 Synchronous version of `fs.readFile`. Returns the contents of the `filename`.
445
446 If the `encoding` option is specified then this function returns a
447 string. Otherwise it returns a buffer.
448
449
450 ## fs.writeFile(filename, data, [options], callback)
451
452 * `filename` {String}
453 * `data` {String | Buffer}
454 * `options` {Object}
455   * `encoding` {String | Null} default = `'utf8'`
456   * `mode` {Number} default = `438` (aka `0666` in Octal)
457   * `flag` {String} default = `'w'`
458 * `callback` {Function}
459
460 Asynchronously writes data to a file, replacing the file if it already exists.
461 `data` can be a string or a buffer.
462
463 The `encoding` option is ignored if `data` is a buffer. It defaults
464 to `'utf8'`.
465
466 Example:
467
468     fs.writeFile('message.txt', 'Hello Node', function (err) {
469       if (err) throw err;
470       console.log('It\'s saved!');
471     });
472
473 ## fs.writeFileSync(filename, data, [options])
474
475 The synchronous version of `fs.writeFile`.
476
477 ## fs.appendFile(filename, data, [options], callback)
478
479 * `filename` {String}
480 * `data` {String | Buffer}
481 * `options` {Object}
482   * `encoding` {String | Null} default = `'utf8'`
483   * `mode` {Number} default = `438` (aka `0666` in Octal)
484   * `flag` {String} default = `'a'`
485 * `callback` {Function}
486
487 Asynchronously append data to a file, creating the file if it not yet exists.
488 `data` can be a string or a buffer.
489
490 Example:
491
492     fs.appendFile('message.txt', 'data to append', function (err) {
493       if (err) throw err;
494       console.log('The "data to append" was appended to file!');
495     });
496
497 ## fs.appendFileSync(filename, data, [options])
498
499 The synchronous version of `fs.appendFile`.
500
501 ## fs.watchFile(filename, [options], listener)
502
503     Stability: 2 - Unstable.  Use fs.watch instead, if possible.
504
505 Watch for changes on `filename`. The callback `listener` will be called each
506 time the file is accessed.
507
508 The second argument is optional. The `options` if provided should be an object
509 containing two members a boolean, `persistent`, and `interval`. `persistent`
510 indicates whether the process should continue to run as long as files are
511 being watched. `interval` indicates how often the target should be polled,
512 in milliseconds. The default is `{ persistent: true, interval: 5007 }`.
513
514 The `listener` gets two arguments the current stat object and the previous
515 stat object:
516
517     fs.watchFile('message.text', function (curr, prev) {
518       console.log('the current mtime is: ' + curr.mtime);
519       console.log('the previous mtime was: ' + prev.mtime);
520     });
521
522 These stat objects are instances of `fs.Stat`.
523
524 If you want to be notified when the file was modified, not just accessed
525 you need to compare `curr.mtime` and `prev.mtime`.
526
527 ## fs.unwatchFile(filename, [listener])
528
529     Stability: 2 - Unstable.  Use fs.watch instead, if available.
530
531 Stop watching for changes on `filename`. If `listener` is specified, only that
532 particular listener is removed. Otherwise, *all* listeners are removed and you
533 have effectively stopped watching `filename`.
534
535 Calling `fs.unwatchFile()` with a filename that is not being watched is a
536 no-op, not an error.
537
538 ## fs.watch(filename, [options], [listener])
539
540     Stability: 2 - Unstable.
541
542 Watch for changes on `filename`, where `filename` is either a file or a
543 directory.  The returned object is a [fs.FSWatcher](#fs_class_fs_fswatcher).
544
545 The second argument is optional. The `options` if provided should be an object
546 containing a boolean member `persistent`, which indicates whether the process
547 should continue to run as long as files are being watched. The default is
548 `{ persistent: true }`.
549
550 The listener callback gets two arguments `(event, filename)`.  `event` is either
551 'rename' or 'change', and `filename` is the name of the file which triggered
552 the event.
553
554 ### Caveats
555
556 <!--type=misc-->
557
558 The `fs.watch` API is not 100% consistent across platforms, and is
559 unavailable in some situations.
560
561 #### Availability
562
563 <!--type=misc-->
564
565 This feature depends on the underlying operating system providing a way
566 to be notified of filesystem changes.
567
568 * On Linux systems, this uses `inotify`.
569 * On BSD systems (including OS X), this uses `kqueue`.
570 * On SunOS systems (including Solaris and SmartOS), this uses `event ports`.
571 * On Windows systems, this feature depends on `ReadDirectoryChangesW`.
572
573 If the underlying functionality is not available for some reason, then
574 `fs.watch` will not be able to function.  For example, watching files or
575 directories on network file systems (NFS, SMB, etc.) often doesn't work
576 reliably or at all.
577
578 You can still use `fs.watchFile`, which uses stat polling, but it is slower and
579 less reliable.
580
581 #### Filename Argument
582
583 <!--type=misc-->
584
585 Providing `filename` argument in the callback is not supported
586 on every platform (currently it's only supported on Linux and Windows).  Even
587 on supported platforms `filename` is not always guaranteed to be provided.
588 Therefore, don't assume that `filename` argument is always provided in the
589 callback, and have some fallback logic if it is null.
590
591     fs.watch('somedir', function (event, filename) {
592       console.log('event is: ' + event);
593       if (filename) {
594         console.log('filename provided: ' + filename);
595       } else {
596         console.log('filename not provided');
597       }
598     });
599
600 ## fs.exists(path, callback)
601
602 Test whether or not the given path exists by checking with the file system.
603 Then call the `callback` argument with either true or false.  Example:
604
605     fs.exists('/etc/passwd', function (exists) {
606       util.debug(exists ? "it's there" : "no passwd!");
607     });
608
609
610 ## fs.existsSync(path)
611
612 Synchronous version of `fs.exists`.
613
614 ## Class: fs.Stats
615
616 Objects returned from `fs.stat()`, `fs.lstat()` and `fs.fstat()` and their
617 synchronous counterparts are of this type.
618
619  - `stats.isFile()`
620  - `stats.isDirectory()`
621  - `stats.isBlockDevice()`
622  - `stats.isCharacterDevice()`
623  - `stats.isSymbolicLink()` (only valid with  `fs.lstat()`)
624  - `stats.isFIFO()`
625  - `stats.isSocket()`
626
627 For a regular file `util.inspect(stats)` would return a string very
628 similar to this:
629
630     { dev: 2114,
631       ino: 48064969,
632       mode: 33188,
633       nlink: 1,
634       uid: 85,
635       gid: 100,
636       rdev: 0,
637       size: 527,
638       blksize: 4096,
639       blocks: 8,
640       atime: Mon, 10 Oct 2011 23:24:11 GMT,
641       mtime: Mon, 10 Oct 2011 23:24:11 GMT,
642       ctime: Mon, 10 Oct 2011 23:24:11 GMT }
643
644 Please note that `atime`, `mtime` and `ctime` are instances
645 of [Date][MDN-Date] object and to compare the values of
646 these objects you should use appropriate methods. For most
647 general uses [getTime()][MDN-Date-getTime] will return
648 the number of milliseconds elapsed since _1 January 1970
649 00:00:00 UTC_ and this integer should be sufficient for
650 any comparison, however there additional methods which can
651 be used for displaying fuzzy information. More details can
652 be found in the [MDN JavaScript Reference][MDN-Date] page.
653
654 [MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
655 [MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
656
657
658 ## fs.createReadStream(path, [options])
659
660 Returns a new ReadStream object (See `Readable Stream`).
661
662 `options` is an object with the following defaults:
663
664     { flags: 'r',
665       encoding: null,
666       fd: null,
667       mode: 0666,
668       bufferSize: 64 * 1024,
669       autoClose: true
670     }
671
672 `options` can include `start` and `end` values to read a range of bytes from
673 the file instead of the entire file.  Both `start` and `end` are inclusive and
674 start at 0. The `encoding` can be `'utf8'`, `'ascii'`, or `'base64'`.
675
676 If `autoClose` is false, then the file descriptor won't be closed, even if
677 there's an error.  It is your responsibility to close it and make sure
678 there's no file descriptor leak.  If `autoClose` is set to true (default
679 behavior), on `error` or `end` the file descriptor will be closed
680 automatically.
681
682 An example to read the last 10 bytes of a file which is 100 bytes long:
683
684     fs.createReadStream('sample.txt', {start: 90, end: 99});
685
686
687 ## Class: fs.ReadStream
688
689 `ReadStream` is a [Readable Stream](stream.html#stream_readable_stream).
690
691 ### Event: 'open'
692
693 * `fd` {Integer} file descriptor used by the ReadStream.
694
695 Emitted when the ReadStream's file is opened.
696
697
698 ## fs.createWriteStream(path, [options])
699
700 Returns a new WriteStream object (See `Writable Stream`).
701
702 `options` is an object with the following defaults:
703
704     { flags: 'w',
705       encoding: null,
706       mode: 0666 }
707
708 `options` may also include a `start` option to allow writing data at
709 some position past the beginning of the file.  Modifying a file rather
710 than replacing it may require a `flags` mode of `r+` rather than the
711 default mode `w`.
712
713 ## fs.WriteStream
714
715 `WriteStream` is a [Writable Stream](stream.html#stream_writable_stream).
716
717 ### Event: 'open'
718
719 * `fd` {Integer} file descriptor used by the WriteStream.
720
721 Emitted when the WriteStream's file is opened.
722
723 ### file.bytesWritten
724
725 The number of bytes written so far. Does not include data that is still queued
726 for writing.
727
728 ## Class: fs.FSWatcher
729
730 Objects returned from `fs.watch()` are of this type.
731
732 ### watcher.close()
733
734 Stop watching for changes on the given `fs.FSWatcher`.
735
736 ### Event: 'change'
737
738 * `event` {String} The type of fs change
739 * `filename` {String} The filename that changed (if relevant/available)
740
741 Emitted when something changes in a watched directory or file.
742 See more details in [fs.watch](#fs_fs_watch_filename_options_listener).
743
744 ### Event: 'error'
745
746 * `error` {Error object}
747
748 Emitted when an error occurs.