@@ -3592,8 +3592,12 @@ changes:
35923592* ` callback ` {Function}
35933593 * ` err ` {Error}
35943594
3595- Asynchronously writes data to a file, replacing the file if it already exists.
3596- ` data ` can be a string or a buffer.
3595+ When ` file ` is a filename, asynchronously writes data to the file, replacing the
3596+ file if it already exists. ` data ` can be a string or a buffer.
3597+
3598+ When ` file ` is a file descriptor, the behavior is similar to calling
3599+ ` fs.write() ` directly (which is recommended). See the notes below on using
3600+ a file descriptor.
35973601
35983602The ` encoding ` option is ignored if ` data ` is a buffer.
35993603
@@ -3615,15 +3619,30 @@ It is unsafe to use `fs.writeFile()` multiple times on the same file without
36153619waiting for the callback. For this scenario, [ ` fs.createWriteStream() ` ] [ ] is
36163620recommended.
36173621
3618- ### File Descriptors
3619- 1 . Any specified file descriptor has to support writing.
3620- 2 . If a file descriptor is specified as the ` file ` , it will not be closed
3621- automatically.
3622- 3 . The writing will begin at the current position. For example, if the string
3623- ` 'Hello' ` is written to the file descriptor, and if ` ', World' ` is written with
3624- ` fs.writeFile() ` to the same file descriptor, the contents of the file would
3625- become ` 'Hello, World' ` , instead of just ` ', World' ` .
3622+ ### Using ` fs.writeFile() ` with File Descriptors
3623+
3624+ When ` file ` is a file descriptor, the behavior is almost identical to directly
3625+ calling ` fs.write() ` like:
3626+ ``` javascript
3627+ fs .write (fd, Buffer .from (data, options .encoding ), callback);
3628+ ```
36263629
3630+ The difference from directly calling ` fs.write() ` is that under some unusual
3631+ conditions, ` fs.write() ` may write only part of the buffer and will need to be
3632+ retried to write the remaining data, whereas ` fs.writeFile() ` will retry until
3633+ the data is entirely written (or an error occurs).
3634+
3635+ Since the implications of this are a common source of confusion, note that in
3636+ the file descriptor case the file is not replaced! The data is not necessarily
3637+ written to the beginning of the file, and the file's original data may remain
3638+ before and/or after the newly written data.
3639+
3640+ For example, if ` fs.writeFile() ` is called twice in a row, first to write the
3641+ string ` 'Hello' ` , then to write the string ` ', World' ` , the file would contain
3642+ ` 'Hello, World' ` , and might contain some of the file's original data (depending
3643+ on the size of the original file, and the position of the file descriptor). If
3644+ a file name had been used instead of a descriptor, the file would be guaranteed
3645+ to contain only ` ', World' ` .
36273646
36283647## fs.writeFileSync(file, data[ , options] )
36293648<!-- YAML
0 commit comments