fs.readFile(path[,
options], callback)
Note
This
method read the file asynchronously. ‘callback’ function is called with
contents of the file.
Below
table summarizes the arguments of readFile method.
Argument
|
Type
|
Description
|
|||||||||
path
|
string
or Buffer or URL or Integer
|
Specifies
the file path or file descriptor.
|
|||||||||
options
|
string
or Object
|
Below
table summarizes different options supported by readFile method.
Abc
|
|||||||||
callback
|
Function
|
Whenever
file data is read, call back function is called with two arguments. Below
table summarizes the arguments of callback function.
|
Since
this method read all the content of the file to in-memory, use the method
‘fs.createReadStream()’, while working with big files.
Let’s
say input.txt contains below information.
input.txt
Two
roads diverged in a yellow wood,
Jb_modern_frost_2_eAnd
sorry I could not travel both
And
be one traveler, long I stood
And
looked down one as far as I could
To
where it bent in the undergrowth;
HelloWorld.js
var
fs = require('fs');
var
filePath = 'input.txt';
var
contents = fs.readFile(filePath, 'utf-8', (err, data) => {
if (err)
return console.error(error);
console.log(data);
});
console.log('Done.......')
Output
Done.......
Two
roads diverged in a yellow wood,
Jb_modern_frost_2_eAnd
sorry I could not travel both
And
be one traveler, long I stood
And
looked down one as far as I could
To
where it bent in the undergrowth;
If
you do not specify the encoding, readFile method returns the Buffer.
HelloWorld.js
var
fs = require('fs');
var
filePath = 'input.txt';
var
contents = fs.readFile(filePath, (err, data) => {
if (err)
return console.error(error);
console.log(data);
});
console.log('Done.......')
Output
Done.......
<Buffer
54 77 6f 20 72 6f 61 64 73 20 64 69 76 65 72 67 65 64 20 69 6e 20 61 20 79 65
6c 6c 6f 77 20 77 6f 6f 64 2c 0d 0a 4a 62 5f 6d 6f 64 65 72 6e 5f 66 72 ...
>
No comments:
Post a Comment