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