Node File System I/O

Read and return a file’s contents

In a recent development project we were required to implement a file open & read using Nodejs. Nodejs supports this with it’s FS module. The module’s functions adhere to POSIX (portable operating system interface) standards. All the methods have asynchronous and synchronous forms. I will focus on asynchronous read file method fs.readfile.

The first step will be to include the Nodejs module in the .js file which is handled by a require statement:

var fs = require( ‘fs’ );

Next the function itself:

fs.readFile( ‘file’ [,encoding], callback( error, data ));

The pathed file name as string will be the first argument. Encoding is optional and if not specified it will be the raw buffer. Options are ‘utf8’, ‘ascii’, and ‘base64’. Lastly a callback function to execute. This callback will be passed two arguments and the first will be for an exception. If operation completed successfully without errors, the first argument will return null or undefined. The last argument will return the actual data.

Show your support

Clapping shows how much you appreciated Kris Stange’s story.