Friday 19 October 2018

node.js: fs.createWriteStream(path[, options]): Working with Writeable stream

fs.createWriteStream(path[, options])
This method creates a writeable stream, used to write data to a file.

Below table summarizes the arguments of createWriteStream method.

Argument
Type
Description
path
string or Buffer or URL
File path to write data.
options
string or Object
Below table summarizes the options supported by createWriteStream method.

Option
Type
Description
flags
string
Default value is ‘r’
encoding
string
Default value is null.
fd
integer
Default value is null. if fd is specified, WriteStream will ignore the path argument and will use the specified file descriptor.
mode
integer
Default value is 0o666.
autoclose
boolean
Default value is true. If autoClose is set to true (default behavior) on 'error' or 'finish' the file descriptor will be closed automatically. If autoClose is false, then the file descriptor won't be closed, even if there's an error.
start
integer
It is used to write data from specific position.

Find he below working application.

HelloWorld.js
var fs = require('fs');

var writeStream = fs.createWriteStream('data.txt');

writeStream.on('finish', () => {
    console.log('*********************');
    console.log('All writes are now complete.');
    console.log('*********************\n');
});

writeStream.on('close', () => {
    console.log('*********************');
    console.log('Closing the stream');
    console.log('*********************');
});

writeStream.write('Hello, How are you\n');
writeStream.write('I am fine, thank you....\n');
writeStream.end('This is the end of the file');

writeStream.close();


Output
*********************
All writes are now complete.
*********************

*********************
Closing the stream
*********************

Open ‘data.txt’, you can see below messages in the console.

Hello, How are you
I am fine, thank you....
This is the end of the file





Previous                                                 Next                                                 Home

No comments:

Post a Comment