forked from nodejs/node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfs.md
More file actions
2855 lines (2324 loc) · 86 KB
/
fs.md
File metadata and controls
2855 lines (2324 loc) · 86 KB
Edit and raw actions
OlderNewer
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
Exceptions may be handled using `try`/`catch`, or they may be allowed to
18
bubble up.
19
20
Here is an example of the asynchronous version:
21
22
```js
23
const fs = require('fs');
24
25
fs.unlink('/tmp/hello', (err) => {
26
if (err) throw err;
27
console.log('successfully deleted /tmp/hello');
28
});
29
```
30
31
Here is the synchronous version:
32
33
```js
34
const fs = require('fs');
35
36
fs.unlinkSync('/tmp/hello');
37
console.log('successfully deleted /tmp/hello');
38
```
39
40
With the asynchronous methods there is no guaranteed ordering. So the
41
following is prone to error:
42
43
```js
44
fs.rename('/tmp/hello', '/tmp/world', (err) => {
45
if (err) throw err;
46
console.log('renamed complete');
47
});
48
fs.stat('/tmp/world', (err, stats) => {
49
if (err) throw err;
50
console.log(`stats: ${JSON.stringify(stats)}`);
51
});
52
```
53
54
It could be that `fs.stat` is executed before `fs.rename`.
55
The correct way to do this is to chain the callbacks.
56
57
```js
58
fs.rename('/tmp/hello', '/tmp/world', (err) => {
59
if (err) throw err;
60
fs.stat('/tmp/world', (err, stats) => {
61
if (err) throw err;
62
console.log(`stats: ${JSON.stringify(stats)}`);
63
});
64
});
65
```
66
67
In busy processes, the programmer is _strongly encouraged_ to use the
68
asynchronous versions of these calls. The synchronous versions will block
69
the entire process until they complete--halting all connections.
70
71
The relative path to a filename can be used. Remember, however, that this path
72
will be relative to `process.cwd()`.
73
74
While it is not recommended, most fs functions allow the callback argument to
75
be omitted, in which case a default callback is used that rethrows errors. To
76
get a trace to the original call site, set the `NODE_DEBUG` environment
77
variable:
78
79
*Note*: Omitting the callback function on asynchronous fs functions is
80
deprecated and may result in an error being thrown in the future.
81
82
```txt
83
$ cat script.js
84
function bad() {
85
require('fs').readFile('/');
86
}
87
bad();
88
89
$ env NODE_DEBUG=fs node script.js
90
fs.js:88
91
throw backtrace;
92
^
93
Error: EISDIR: illegal operation on a directory, read
94
<stack trace.>
95
```
96
97
*Note:* On Windows Node.js follows the concept of per-drive working directory.
98
This behavior can be observed when using a drive path without a backslash. For
99
example `fs.readdirSync('c:\\')` can potentially return a different result than
100
`fs.readdirSync('c:')`. For more information, see
101
[this MSDN page][MSDN-Rel-Path].
102
103
## WHATWG URL object support
104
<!-- YAML
105
added: v7.6.0
106
-->
107
108
> Stability: 1 - Experimental
109
110
For most `fs` module functions, the `path` or `filename` argument may be passed
111
as a WHATWG [`URL`][] object. Only [`URL`][] objects using the `file:` protocol
112
are supported.
113
114
```js
115
const fs = require('fs');
116
const { URL } = require('url');
117
const fileUrl = new URL('file:///tmp/hello');
118
119
fs.readFileSync(fileUrl);
120
```
121
122
*Note*: `file:` URLs are always absolute paths.
123
124
Using WHATWG [`URL`][] objects might introduce platform-specific behaviors.
125
126
On Windows, `file:` URLs with a hostname convert to UNC paths, while `file:`
127
URLs with drive letters convert to local absolute paths. `file:` URLs without a
128
hostname nor a drive letter will result in a throw :
129
130
```js
131
// On Windows :
132
133
// - WHATWG file URLs with hostname convert to UNC path
134
// file://hostname/p/a/t/h/file => \\hostname\p\a\t\h\file
135
fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
136
137
// - WHATWG file URLs with drive letters convert to absolute path
138
// file:///C:/tmp/hello => C:\tmp\hello
139
fs.readFileSync(new URL('file:///C:/tmp/hello'));
140
141
// - WHATWG file URLs without hostname must have a drive letters
142
fs.readFileSync(new URL('file:///notdriveletter/p/a/t/h/file'));
143
fs.readFileSync(new URL('file:///c/p/a/t/h/file'));
144
// TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must be absolute
145
```
146
147
*Note*: `file:` URLs with drive letters must use `:` as a separator just after
148
the drive letter. Using another separator will result in a throw.
149
150
On all other platforms, `file:` URLs with a hostname are unsupported and will
151
result in a throw:
152
153
```js
154
// On other platforms:
155
156
// - WHATWG file URLs with hostname are unsupported
157
// file://hostname/p/a/t/h/file => throw!
158
fs.readFileSync(new URL('file://hostname/p/a/t/h/file'));
159
// TypeError [ERR_INVALID_FILE_URL_PATH]: must be absolute
160
161
// - WHATWG file URLs convert to absolute path
162
// file:///tmp/hello => /tmp/hello
163
fs.readFileSync(new URL('file:///tmp/hello'));
164
```
165
166
A `file:` URL having encoded slash characters will result in a throw on all
167
platforms:
168
169
```js
170
// On Windows
171
fs.readFileSync(new URL('file:///C:/p/a/t/h/%2F'));
172
fs.readFileSync(new URL('file:///C:/p/a/t/h/%2f'));
173
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
174
\ or / characters */
175
176
// On POSIX
177
fs.readFileSync(new URL('file:///p/a/t/h/%2F'));
178
fs.readFileSync(new URL('file:///p/a/t/h/%2f'));
179
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
180
/ characters */
181
```
182
On Windows, `file:` URLs having encoded backslash will result in a throw:
183
184
```js
185
// On Windows
186
fs.readFileSync(new URL('file:///C:/path/%5C'));
187
fs.readFileSync(new URL('file:///C:/path/%5c'));
188
/* TypeError [ERR_INVALID_FILE_URL_PATH]: File URL path must not include encoded
189
\ or / characters */
190
```
191
192
## Buffer API
193
<!-- YAML
194
added: v6.0.0
195
-->
196
197
`fs` functions support passing and receiving paths as both strings
198
and Buffers. The latter is intended to make it possible to work with
199
filesystems that allow for non-UTF-8 filenames. For most typical
200
uses, working with paths as Buffers will be unnecessary, as the string
201
API converts to and from UTF-8 automatically.
202
203
*Note*: On certain file systems (such as NTFS and HFS+) filenames
204
will always be encoded as UTF-8. On such file systems, passing
205
non-UTF-8 encoded Buffers to `fs` functions will not work as expected.
206
207
## Class: fs.FSWatcher
208
<!-- YAML
209
added: v0.5.8
210
-->
211
212
Objects returned from [`fs.watch()`][] are of this type.
213
214
The `listener` callback provided to `fs.watch()` receives the returned FSWatcher's
215
`change` events.
216
217
The object itself emits these events:
218
219
### Event: 'change'
220
<!-- YAML
221
added: v0.5.8
222
-->
223
224
* `eventType` {string} The type of fs change
225
* `filename` {string|Buffer} The filename that changed (if relevant/available)
226
227
Emitted when something changes in a watched directory or file.
228
See more details in [`fs.watch()`][].
229
230
The `filename` argument may not be provided depending on operating system
231
support. If `filename` is provided, it will be provided as a `Buffer` if
232
`fs.watch()` is called with its `encoding` option set to `'buffer'`, otherwise
233
`filename` will be a string.
234
235
```js
236
// Example when handled through fs.watch listener
237
fs.watch('./tmp', { encoding: 'buffer' }, (eventType, filename) => {
238
if (filename)
239
console.log(filename);
240
// Prints: <Buffer ...>
241
});
242
```
243
244
### Event: 'error'
245
<!-- YAML
246
added: v0.5.8
247
-->
248
249
* `error` {Error}
250
251
Emitted when an error occurs.
252
253
### watcher.close()
254
<!-- YAML
255
added: v0.5.8
256
-->
257
258
Stop watching for changes on the given `fs.FSWatcher`.
259
260
## Class: fs.ReadStream
261
<!-- YAML
262
added: v0.1.93
263
-->
264
265
`ReadStream` is a [Readable Stream][].
266
267
### Event: 'close'
268
<!-- YAML
269
added: v0.1.93
270
-->
271
272
Emitted when the `ReadStream`'s underlying file descriptor has been closed
273
using the `fs.close()` method.
274
275
### Event: 'open'
276
<!-- YAML
277
added: v0.1.93
278
-->
279
280
* `fd` {integer} Integer file descriptor used by the ReadStream.
281
282
Emitted when the ReadStream's file is opened.
283
284
### readStream.bytesRead
285
<!-- YAML
286
added: 6.4.0
287
-->
288
289
The number of bytes read so far.
290
291
### readStream.path
292
<!-- YAML
293
added: v0.1.93
294
-->
295
296
The path to the file the stream is reading from as specified in the first
297
argument to `fs.createReadStream()`. If `path` is passed as a string, then
298
`readStream.path` will be a string. If `path` is passed as a `Buffer`, then
299
`readStream.path` will be a `Buffer`.
300
301
## Class: fs.Stats
302
<!-- YAML
303
added: v0.1.21
304
changes:
305
- version: REPLACEME
306
pr-url: https://github.com/nodejs/node/pull/13173
307
description: Added times as numbers.
308
-->
309
310
Objects returned from [`fs.stat()`][], [`fs.lstat()`][] and [`fs.fstat()`][] and
311
their synchronous counterparts are of this type.
312
313
- `stats.isFile()`
314
- `stats.isDirectory()`
315
- `stats.isBlockDevice()`
316
- `stats.isCharacterDevice()`
317
- `stats.isSymbolicLink()` (only valid with [`fs.lstat()`][])
318
- `stats.isFIFO()`
319
- `stats.isSocket()`
320
321
For a regular file [`util.inspect(stats)`][] would return a string very
322
similar to this:
323
324
```console
325
Stats {
326
dev: 2114,
327
ino: 48064969,
328
mode: 33188,
329
nlink: 1,
330
uid: 85,
331
gid: 100,
332
rdev: 0,
333
size: 527,
334
blksize: 4096,
335
blocks: 8,
336
atimeMs: 1318289051000.1,
337
mtimeMs: 1318289051000.1,
338
ctimeMs: 1318289051000.1,
339
birthtimeMs: 1318289051000.1,
340
atime: Mon, 10 Oct 2011 23:24:11 GMT,
341
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
342
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
343
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
344
```
345
346
*Note*: `atimeMs`, `mtimeMs`, `ctimeMs`, `birthtimeMs` are [numbers][MDN-Number]
347
that hold the corresponding times in milliseconds. Their precision is platform
348
specific. `atime`, `mtime`, `ctime`, and `birthtime` are [`Date`][MDN-Date]
349
object alternate representations of the various times. The `Date` and number
350
values are not connected. Assigning a new number value, or mutating the `Date`
351
value, will not be reflected in the corresponding alternate representation.
352
353
354
### Stat Time Values
355
356
The times in the stat object have the following semantics:
357
358
* `atime` "Access Time" - Time when file data last accessed. Changed
359
by the mknod(2), utimes(2), and read(2) system calls.
360
* `mtime` "Modified Time" - Time when file data last modified.
361
Changed by the mknod(2), utimes(2), and write(2) system calls.
362
* `ctime` "Change Time" - Time when file status was last changed
363
(inode data modification). Changed by the chmod(2), chown(2),
364
link(2), mknod(2), rename(2), unlink(2), utimes(2),
365
read(2), and write(2) system calls.
366
* `birthtime` "Birth Time" - Time of file creation. Set once when the
367
file is created. On filesystems where birthtime is not available,
368
this field may instead hold either the `ctime` or
369
`1970-01-01T00:00Z` (ie, unix epoch timestamp `0`). Note that this
370
value may be greater than `atime` or `mtime` in this case. On Darwin
371
and other FreeBSD variants, also set if the `atime` is explicitly
372
set to an earlier value than the current `birthtime` using the
373
utimes(2) system call.
374
375
Prior to Node v0.12, the `ctime` held the `birthtime` on Windows
376
systems. Note that as of v0.12, `ctime` is not "creation time", and
377
on Unix systems, it never was.
378
379
## Class: fs.WriteStream
380
<!-- YAML
381
added: v0.1.93
382
-->
383
384
`WriteStream` is a [Writable Stream][].
385
386
### Event: 'close'
387
<!-- YAML
388
added: v0.1.93
389
-->
390
391
Emitted when the `WriteStream`'s underlying file descriptor has been closed
392
using the `fs.close()` method.
393
394
### Event: 'open'
395
<!-- YAML
396
added: v0.1.93
397
-->
398
399
* `fd` {integer} Integer file descriptor used by the WriteStream.
400
401
Emitted when the WriteStream's file is opened.
402
403
### writeStream.bytesWritten
404
<!-- YAML
405
added: v0.4.7
406
-->
407
408
The number of bytes written so far. Does not include data that is still queued
409
for writing.
410
411
### writeStream.path
412
<!-- YAML
413
added: v0.1.93
414
-->
415
416
The path to the file the stream is writing to as specified in the first
417
argument to `fs.createWriteStream()`. If `path` is passed as a string, then
418
`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then
419
`writeStream.path` will be a `Buffer`.
420
421
## fs.access(path[, mode], callback)
422
<!-- YAML
423
added: v0.11.15
424
changes:
425
- version: v7.6.0
426
pr-url: https://github.com/nodejs/node/pull/10739
427
description: The `path` parameter can be a WHATWG `URL` object using `file:`
428
protocol. Support is currently still *experimental*.
429
-->
430
431
* `path` {string|Buffer|URL}
432
* `mode` {integer}
433
* `callback` {Function}
434
435
Tests a user's permissions for the file or directory specified by `path`.
436
The `mode` argument is an optional integer that specifies the accessibility
437
checks to be performed. The following constants define the possible values of
438
`mode`. It is possible to create a mask consisting of the bitwise OR of two or
439
more values.
440
441
- `fs.constants.F_OK` - `path` is visible to the calling process. This is useful
442
for determining if a file exists, but says nothing about `rwx` permissions.
443
Default if no `mode` is specified.
444
- `fs.constants.R_OK` - `path` can be read by the calling process.
445
- `fs.constants.W_OK` - `path` can be written by the calling process.
446
- `fs.constants.X_OK` - `path` can be executed by the calling process. This has
447
no effect on Windows (will behave like `fs.constants.F_OK`).
448
449
The final argument, `callback`, is a callback function that is invoked with
450
a possible error argument. If any of the accessibility checks fail, the error
451
argument will be populated. The following example checks if the file
452
`/etc/passwd` can be read and written by the current process.
453
454
```js
455
fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
456
console.log(err ? 'no access!' : 'can read/write');
457
});
458
```
459
460
Using `fs.access()` to check for the accessibility of a file before calling
461
`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing
462
so introduces a race condition, since other processes may change the file's
463
state between the two calls. Instead, user code should open/read/write the
464
file directly and handle the error raised if the file is not accessible.
465
466
For example:
467
468
469
**write (NOT RECOMMENDED)**
470
471
```js
472
fs.access('myfile', (err) => {
473
if (!err) {
474
console.error('myfile already exists');
475
return;
476
}
477
478
fs.open('myfile', 'wx', (err, fd) => {
479
if (err) throw err;
480
writeMyData(fd);
481
});
482
});
483
```
484
485
**write (RECOMMENDED)**
486
487
```js
488
fs.open('myfile', 'wx', (err, fd) => {
489
if (err) {
490
if (err.code === 'EEXIST') {
491
console.error('myfile already exists');
492
return;
493
}
494
495
throw err;
496
}
497
498
writeMyData(fd);
499
});
500
```
501
502
**read (NOT RECOMMENDED)**
503
504
```js
505
fs.access('myfile', (err) => {
506
if (err) {
507
if (err.code === 'ENOENT') {
508
console.error('myfile does not exist');
509
return;
510
}
511
512
throw err;
513
}
514
515
fs.open('myfile', 'r', (err, fd) => {
516
if (err) throw err;
517
readMyData(fd);
518
});
519
});
520
```
521
522
**read (RECOMMENDED)**
523
524
```js
525
fs.open('myfile', 'r', (err, fd) => {
526
if (err) {
527
if (err.code === 'ENOENT') {
528
console.error('myfile does not exist');
529
return;
530
}
531
532
throw err;
533
}
534
535
readMyData(fd);
536
});
537
```
538
539
The "not recommended" examples above check for accessibility and then use the
540
file; the "recommended" examples are better because they use the file directly
541
and handle the error, if any.
542
543
In general, check for the accessibility of a file only if the file won’t be
544
used directly, for example when its accessibility is a signal from another
545
process.
546
547
## fs.accessSync(path[, mode])
548
<!-- YAML
549
added: v0.11.15
550
changes:
551
- version: v7.6.0
552
pr-url: https://github.com/nodejs/node/pull/10739
553
description: The `path` parameter can be a WHATWG `URL` object using `file:`
554
protocol. Support is currently still *experimental*.
555
-->
556
557
* `path` {string|Buffer|URL}
558
* `mode` {integer}
559
560
Synchronous version of [`fs.access()`][]. This throws if any accessibility
561
checks fail, and does nothing otherwise.
562
563
## fs.appendFile(file, data[, options], callback)
564
<!-- YAML
565
added: v0.6.7
566
changes:
567
- version: v7.0.0
568
pr-url: https://github.com/nodejs/node/pull/7897
569
description: The `callback` parameter is no longer optional. Not passing
570
it will emit a deprecation warning.
571
- version: v7.0.0
572
pr-url: https://github.com/nodejs/node/pull/7831
573
description: The passed `options` object will never be modified.
574
- version: v5.0.0
575
pr-url: https://github.com/nodejs/node/pull/3163
576
description: The `file` parameter can be a file descriptor now.
577
-->
578
579
* `file` {string|Buffer|number} filename or file descriptor
580
* `data` {string|Buffer}
581
* `options` {Object|string}
582
* `encoding` {string|null} default = `'utf8'`
583
* `mode` {integer} default = `0o666`
584
* `flag` {string} default = `'a'`
585
* `callback` {Function}
586
587
Asynchronously append data to a file, creating the file if it does not yet exist.
588
`data` can be a string or a buffer.
589
590
Example:
591
592
```js
593
fs.appendFile('message.txt', 'data to append', (err) => {
594
if (err) throw err;
595
console.log('The "data to append" was appended to file!');
596
});
597
```
598
599
If `options` is a string, then it specifies the encoding. Example:
600
601
```js
602
fs.appendFile('message.txt', 'data to append', 'utf8', callback);
603
```
604
605
Any specified file descriptor has to have been opened for appending.
606
607
*Note*: If a file descriptor is specified as the `file`, it will not be closed
608
automatically.
609
610
## fs.appendFileSync(file, data[, options])
611
<!-- YAML
612
added: v0.6.7
613
changes:
614
- version: v7.0.0
615
pr-url: https://github.com/nodejs/node/pull/7831
616
description: The passed `options` object will never be modified.
617
- version: v5.0.0
618
pr-url: https://github.com/nodejs/node/pull/3163
619
description: The `file` parameter can be a file descriptor now.
620
-->
621
622
* `file` {string|Buffer|number} filename or file descriptor
623
* `data` {string|Buffer}
624
* `options` {Object|string}
625
* `encoding` {string|null} default = `'utf8'`
626
* `mode` {integer} default = `0o666`
627
* `flag` {string} default = `'a'`
628
629
The synchronous version of [`fs.appendFile()`][]. Returns `undefined`.
630
631
## fs.chmod(path, mode, callback)
632
<!-- YAML
633
added: v0.1.30
634
changes:
635
- version: v7.6.0
636
pr-url: https://github.com/nodejs/node/pull/10739
637
description: The `path` parameter can be a WHATWG `URL` object using `file:`
638
protocol. Support is currently still *experimental*.
639
- version: v7.0.0
640
pr-url: https://github.com/nodejs/node/pull/7897
641
description: The `callback` parameter is no longer optional. Not passing
642
it will emit a deprecation warning.
643
-->
644
645
* `path` {string|Buffer|URL}
646
* `mode` {integer}
647
* `callback` {Function}
648
649
Asynchronous chmod(2). No arguments other than a possible exception are given
650
to the completion callback.
651
652
## fs.chmodSync(path, mode)
653
<!-- YAML
654
added: v0.6.7
655
changes:
656
- version: v7.6.0
657
pr-url: https://github.com/nodejs/node/pull/10739
658
description: The `path` parameter can be a WHATWG `URL` object using `file:`
659
protocol. Support is currently still *experimental*.
660
-->
661
662
* `path` {string|Buffer|URL}
663
* `mode` {integer}
664
665
Synchronous chmod(2). Returns `undefined`.
666
667
## fs.chown(path, uid, gid, callback)
668
<!-- YAML
669
added: v0.1.97
670
changes:
671
- version: v7.6.0
672
pr-url: https://github.com/nodejs/node/pull/10739
673
description: The `path` parameter can be a WHATWG `URL` object using `file:`
674
protocol. Support is currently still *experimental*.
675
- version: v7.0.0
676
pr-url: https://github.com/nodejs/node/pull/7897
677
description: The `callback` parameter is no longer optional. Not passing
678
it will emit a deprecation warning.
679
-->
680
681
* `path` {string|Buffer|URL}
682
* `uid` {integer}
683
* `gid` {integer}
684
* `callback` {Function}
685
686
Asynchronous chown(2). No arguments other than a possible exception are given
687
to the completion callback.
688
689
## fs.chownSync(path, uid, gid)
690
<!-- YAML
691
added: v0.1.97
692
changes:
693
- version: v7.6.0
694
pr-url: https://github.com/nodejs/node/pull/10739
695
description: The `path` parameter can be a WHATWG `URL` object using `file:`
696
protocol. Support is currently still *experimental*.
697
-->
698
699
* `path` {string|Buffer|URL}
700
* `uid` {integer}
701
* `gid` {integer}
702
703
Synchronous chown(2). Returns `undefined`.
704
705
## fs.close(fd, callback)
706
<!-- YAML
707
added: v0.0.2
708
changes:
709
- version: v7.0.0
710
pr-url: https://github.com/nodejs/node/pull/7897
711
description: The `callback` parameter is no longer optional. Not passing
712
it will emit a deprecation warning.
713
-->
714
715
* `fd` {integer}
716
* `callback` {Function}
717
718
Asynchronous close(2). No arguments other than a possible exception are given
719
to the completion callback.
720
721
## fs.closeSync(fd)
722
<!-- YAML
723
added: v0.1.21
724
-->
725
726
* `fd` {integer}
727
728
Synchronous close(2). Returns `undefined`.
729
730
## fs.constants
731
732
Returns an object containing commonly used constants for file system
733
operations. The specific constants currently defined are described in
734
[FS Constants][].
735
736
## fs.createReadStream(path[, options])
737
<!-- YAML
738
added: v0.1.31
739
changes:
740
- version: v7.6.0
741
pr-url: https://github.com/nodejs/node/pull/10739
742
description: The `path` parameter can be a WHATWG `URL` object using
743
`file:` protocol. Support is currently still *experimental*.
744
- version: v7.0.0
745
pr-url: https://github.com/nodejs/node/pull/7831
746
description: The passed `options` object will never be modified.
747
- version: v2.3.0
748
pr-url: https://github.com/nodejs/node/pull/1845
749
description: The passed `options` object can be a string now.
750
-->
751
752
* `path` {string|Buffer|URL}
753
* `options` {string|Object}
754
* `flags` {string}
755
* `encoding` {string}
756
* `fd` {integer}
757
* `mode` {integer}
758
* `autoClose` {boolean}
759
* `start` {integer}
760
* `end` {integer}
761
762
Returns a new [`ReadStream`][] object. (See [Readable Stream][]).
763
764
Be aware that, unlike the default value set for `highWaterMark` on a
765
readable stream (16 kb), the stream returned by this method has a
766
default value of 64 kb for the same parameter.
767
768
`options` is an object or string with the following defaults:
769
770
```js
771
const defaults = {
772
flags: 'r',
773
encoding: null,
774
fd: null,
775
mode: 0o666,
776
autoClose: true
777
};
778
```
779
780
`options` can include `start` and `end` values to read a range of bytes from
781
the file instead of the entire file. Both `start` and `end` are inclusive and
782
start counting at 0. If `fd` is specified and `start` is omitted or `undefined`,
783
`fs.createReadStream()` reads sequentially from the current file position.
784
The `encoding` can be any one of those accepted by [`Buffer`][].
785
786
If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
787
the specified file descriptor. This means that no `'open'` event will be
788
emitted. Note that `fd` should be blocking; non-blocking `fd`s should be passed
789
to [`net.Socket`][].
790
791
If `autoClose` is false, then the file descriptor won't be closed, even if
792
there's an error. It is the application's responsibility to close it and make
793
sure there's no file descriptor leak. If `autoClose` is set to true (default
794
behavior), on `error` or `end` the file descriptor will be closed
795
automatically.
796
797
`mode` sets the file mode (permission and sticky bits), but only if the
798
file was created.
799
800
An example to read the last 10 bytes of a file which is 100 bytes long:
801
802
```js
803
fs.createReadStream('sample.txt', { start: 90, end: 99 });
804
```
805
806
If `options` is a string, then it specifies the encoding.
807
808
## fs.createWriteStream(path[, options])
809
<!-- YAML
810
added: v0.1.31
811
changes:
812
- version: v7.6.0
813
pr-url: https://github.com/nodejs/node/pull/10739
814
description: The `path` parameter can be a WHATWG `URL` object using
815
`file:` protocol. Support is currently still *experimental*.
816
- version: v7.0.0
817
pr-url: https://github.com/nodejs/node/pull/7831
818
description: The passed `options` object will never be modified.
819
- version: v5.5.0
820
pr-url: https://github.com/nodejs/node/pull/3679
821
description: The `autoClose` option is supported now.
822
- version: v2.3.0
823
pr-url: https://github.com/nodejs/node/pull/1845
824
description: The passed `options` object can be a string now.
825
-->
826
827
* `path` {string|Buffer|URL}
828
* `options` {string|Object}
829
* `flags` {string}
830
* `defaultEncoding` {string}
831
* `fd` {integer}
832
* `mode` {integer}
833
* `autoClose` {boolean}
834
* `start` {integer}
835
836
Returns a new [`WriteStream`][] object. (See [Writable Stream][]).
837
838
`options` is an object or string with the following defaults:
839
840
```js
841
const defaults = {
842
flags: 'w',
843
defaultEncoding: 'utf8',
844
fd: null,
845
mode: 0o666,
846
autoClose: true
847
};
848
```
849
850
`options` may also include a `start` option to allow writing data at
851
some position past the beginning of the file. Modifying a file rather
852
than replacing it may require a `flags` mode of `r+` rather than the
853
default mode `w`. The `defaultEncoding` can be any one of those accepted by
854
[`Buffer`][].
855
856
If `autoClose` is set to true (default behavior) on `error` or `end`
857
the file descriptor will be closed automatically. If `autoClose` is false,
858
then the file descriptor won't be closed, even if there's an error.
859
It is the application's responsibility to close it and make sure there's no
860
file descriptor leak.
861
862
Like [`ReadStream`][], if `fd` is specified, `WriteStream` will ignore the
863
`path` argument and will use the specified file descriptor. This means that no
864
`'open'` event will be emitted. Note that `fd` should be blocking; non-blocking
865
`fd`s should be passed to [`net.Socket`][].
866
867
If `options` is a string, then it specifies the encoding.
868
869
## fs.exists(path, callback)
870
<!-- YAML
871
added: v0.0.2
872
changes:
873
- version: v7.6.0
874
pr-url: https://github.com/nodejs/node/pull/10739
875
description: The `path` parameter can be a WHATWG `URL` object using
876
`file:` protocol. Support is currently still *experimental*.
877
deprecated: v1.0.0
878
-->
879
880
> Stability: 0 - Deprecated: Use [`fs.stat()`][] or [`fs.access()`][] instead.
881
882
* `path` {string|Buffer|URL}
883
* `callback` {Function}
884
885
Test whether or not the given path exists by checking with the file system.
886
Then call the `callback` argument with either true or false. Example:
887
888
```js
889
fs.exists('/etc/passwd', (exists) => {
890
console.log(exists ? 'it\'s there' : 'no passwd!');
891
});
892
```
893
894
**Note that the parameter to this callback is not consistent with other
895
Node.js callbacks.** Normally, the first parameter to a Node.js callback is
896
an `err` parameter, optionally followed by other parameters. The
897
`fs.exists()` callback has only one boolean parameter. This is one reason
898
`fs.access()` is recommended instead of `fs.exists()`.
899
900
Using `fs.exists()` to check for the existence of a file before calling
901
`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing
902
so introduces a race condition, since other processes may change the file's
903
state between the two calls. Instead, user code should open/read/write the
904
file directly and handle the error raised if the file does not exist.
905
906
For example:
907
908
**write (NOT RECOMMENDED)**
909
910
```js
911
fs.exists('myfile', (exists) => {
912
if (exists) {
913
console.error('myfile already exists');
914
} else {
915
fs.open('myfile', 'wx', (err, fd) => {
916
if (err) throw err;
917
writeMyData(fd);
918
});
919
}
920
});
921
```
922
923
**write (RECOMMENDED)**
924
925
```js
926
fs.open('myfile', 'wx', (err, fd) => {
927
if (err) {
928
if (err.code === 'EEXIST') {
929
console.error('myfile already exists');
930
return;
931
}
932
933
throw err;
934
}
935
936
writeMyData(fd);
937
});
938
```
939
940
**read (NOT RECOMMENDED)**
941
942
```js
943
fs.exists('myfile', (exists) => {
944
if (exists) {
945
fs.open('myfile', 'r', (err, fd) => {
946
readMyData(fd);
947
});
948
} else {
949
console.error('myfile does not exist');
950
}
951
});
952
```
953
954
**read (RECOMMENDED)**
955
956
```js
957
fs.open('myfile', 'r', (err, fd) => {
958
if (err) {
959
if (err.code === 'ENOENT') {
960
console.error('myfile does not exist');
961
return;
962
}
963
964
throw err;
965
}
966
967
readMyData(fd);
968
});
969
```
970
971
The "not recommended" examples above check for existence and then use the
972
file; the "recommended" examples are better because they use the file directly
973
and handle the error, if any.
974
975
In general, check for the existence of a file only if the file won’t be
976
used directly, for example when its existence is a signal from another
977
process.
978
979
## fs.existsSync(path)
980
<!-- YAML
981
added: v0.1.21
982
changes:
983
- version: v7.6.0
984
pr-url: https://github.com/nodejs/node/pull/10739
985
description: The `path` parameter can be a WHATWG `URL` object using
986
`file:` protocol. Support is currently still *experimental*.
987
-->
988
989
* `path` {string|Buffer|URL}
990
991
Synchronous version of [`fs.exists()`][].
992
Returns `true` if the file exists, `false` otherwise.
993
994
Note that `fs.exists()` is deprecated, but `fs.existsSync()` is not.
995
(The `callback` parameter to `fs.exists()` accepts parameters that are
996
inconsistent with other Node.js callbacks. `fs.existsSync()` does not use
997
a callback.)
998
999
## fs.fchmod(fd, mode, callback)
1000
<!-- YAML