Skip to content

Commit cc40f8f

Browse files
authored
Added flags : 'a' option to fs.createWriteStream (#4963)
* Added flags : 'a' option to fs.createWriteStream Without flags : 'a' option nothing is saved in output.txt file * Added note about 'flags':'a' option in 'fs.createWriteStream()' call.
1 parent 99cefff commit cc40f8f

File tree

1 file changed

+2
-1
lines changed

1 file changed

+2
-1
lines changed

locale/en/knowledge/advanced/streams/how-to-use-fs-create-write-stream.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,15 @@ layout: knowledge-post.hbs
1010
---
1111

1212
The function `fs.createWriteStream()` creates a writable stream in a very simple manner. After a call to `fs.createWriteStream()` with the filepath, you have a writeable stream to work with. It turns out that the response (as well as the request) objects are streams. So we will stream the `POST` data to the file `output`. Since the code is simple enough, it is pretty easy just to read through it and comment why each line is necessary.
13+
Note: With the default `flags`:`w` option, the `fs.createWriteStream()` function opens a file for writing. The file is created (if it does not exist) or truncated (if it exists). Since most browsers send more than one request to a server at a time, each new request, and therefore each new `fs.createWriteStream()` call deletes any existing data from the `output` file. So, to ensure that no possible subsequent requests remove data written by the `POST` request with the data from the `<form>` element, the `flags`:`a` option is added to the `fs.createWriteStream()` call, which then opens a file for appending data (any existing data remains unaffected).
1314

1415
```javascript
1516
var http = require('http');
1617
var fs = require('fs');
1718

1819
http.createServer(function(req, res) {
1920
// This opens up the writeable stream to `output`
20-
var writeStream = fs.createWriteStream('./output');
21+
var writeStream = fs.createWriteStream('./output', {flags:'a'});
2122

2223
// This pipes the POST data to the file
2324
req.pipe(writeStream);

0 commit comments

Comments
 (0)