Wednesday 17 October 2018

Node.js: fs.readFileSync(path[, options]): Return the contents of the file

fs.readFileSync(path[, options])
This method read the contents of the file synchronously.

Below table summarizes the arguments of readFileSync method.
Argument
Type
Description
path
string or Buffer or URL or integer
Specifies the filename of file descriptor.
options
Object or string
Below table summarizes different options supported by readFileSync method.

Option
Type
Description
encoding
string
Default value is null. If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
flag
string
Default value is 'r'. Following modes are supported by node.js.

'a' - Open file for appending. The file is created if it does not exist.

'ax' - Like 'a' but fails if the path exists.

'a+' - Open file for reading and appending. The file is created if it does not exist.

'ax+' - Like 'a+' but fails if the path exists.

'as' - Open file for appending in synchronous mode. The file is created if it does not exist.

'as+' - Open file for reading and appending in synchronous mode. The file is created if it does not exist.

'r' - Open file for reading. An exception occurs if the file does not exist.

'r+' - Open file for reading and writing. An exception occurs if the file does not exist.

'rs+' - Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache.

Find the below working application.

Let ‘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.readFileSync(filePath, 'UTF-8');

console.log(contents);

console.log('Done.......')

Output

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;

Done.......

If you do not specify encoding, ‘readFileSync’ method returns a buffer.

HelloWorld.js

var fs = require('fs');

var filePath = 'input.txt';

var contents = fs.readFileSync(filePath);

console.log(contents);

console.log('Done.......')



Previous                                                 Next                                                 Home

No comments:

Post a Comment