loading...

NodeJS http homepage 40: using File System module for read a file with readFile()

antelove19 profile image Falah Al Fitri ・2 min read

Happy Coding

previous post


File System1 module is one of powerfull built-in module in NodeJS.

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

Example:

fs.readFile( '/etc/passwd', function ( err, data ) {

    if (err) throw err;

    console.log(data);

} );

In this post, we will set content of html static into each html files and using readFile() method for read all of them.

Ok, let's begin:

create a file "home": public/home.html and write code such as:

<h1>Hello World in NodeJS HTTP</h1>
<p>NodeJS easy-to-learn</p>

create a file "about": public/about.html and write code such as:

<h1>About me</h1>
<p>I am developer</p>
<p>I love programming</p>

create a file "404": public/404.html and write code such as:

<h1>404</h1>
<p>Page not found</p>

After that, back to index.js and add File System module:

const fs    = require('fs');

Inside if ( req.url == '/' ), replace

res.write( '<h1>Hello World in NodeJS HTTP</h1>' );
res.write( '<p>NodeJS easy-to-learn</p>' );

with

fs.readFile( './public/home.html', 'utf8', function ( err, data ) {

    res.write( data );

    res.end();

} );

Inside else if ( req.url == '/about'), replace

res.write( "<h1>About me</h1>" );
res.write( "<p>I am developer</p>" );
res.write( "<p>I love programming</p>" );

with

fs.readFile( './public/about.html', 'utf8', function ( err, data ) {

    res.write( data );

    res.end();

} );

Inside else, replace

res.write( "<h1>404</h1>" );        
res.write( '<p>Page not found</p>' );

with

fs.readFile( './public/404.html', 'utf8', function ( err, data ) {

    res.writeHead( 404, { 'Content-Type': 'text/html' } );

    res.write( data );

    res.end();

} );

Done.


Thank for reading :)


  1. nodejs.org File System::readFile() on date 20 december 2019 and accessed from: https://nodejs.org/docs/latest-v10.x/api/fs.html#fs_fs_readfile_path_options_callback 

Discussion

pic
Editor guide