Sunday 16 September 2018

fs.readFile() and fs.readFileSync()

Today I would like to discuss fs.readFile() and fs.readFileSync().

fs.readFile(path[, options], callback)

fs.readFile() is used to asynchronously read files. It takes up to 3 parameters:
path - can be string, Buffer, URL or integer. It specifies filename or file descriptor.
options - can be encoding string or null (example: 'utf8')
               or flag string (examples: 'a', 'as', 'w+'). Full list you can see here.
callback function takes 2 parameters:
Error err
and string or Buffer data that stores the contents of the file.

When you use this function, remember the following rules:

  • If you don't specify the encoding, the raw buffer is returned.
  • If you specify file descriptor, it has to include reading possibility.
  • This function buffers the entire file. If you care about memory, you might want to use another way of reading files.


Here is a sample code:

fs.readFile('demofile1.html'function(err, data) {
    res.writeHead(200, {'Content-Type''text/html'});
    res.write(data);
    res.end();
}


fs.readFileSync(path[, options])

fs.readFileSync() is used to synchronously read files. It takes up to 2 parameters:

path - can be string, Buffer, URL or integer. It specifies filename or file descriptor.
options - can be encoding string or null (example: 'utf8')
                           or flag string (examples: 'a', 'as', 'w+'). Full list you can see here.

Rules mentioned about fs.readFile() also apply to fs.readFileSync().

Here is a sample code:

fs.readFile('demofile1.html');

Sources:
https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options
https://www.w3schools.com/nodejs/nodejs_filesystem.asp

No comments:

Post a Comment