DEV Community

Falah Al Fitri
Falah Al Fitri

Posted on

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


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);

} );
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

<h1>404</h1>
<p>Page not found</p>
Enter fullscreen mode Exit fullscreen mode

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

const fs    = require('fs');
Enter fullscreen mode Exit fullscreen mode

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

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

with

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

    res.write( data );

    res.end();

} );
Enter fullscreen mode Exit fullscreen mode

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>" );
Enter fullscreen mode Exit fullscreen mode

with

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

    res.write( data );

    res.end();

} );
Enter fullscreen mode Exit fullscreen mode

Inside else, replace

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

with

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

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

    res.write( data );

    res.end();

} );
Enter fullscreen mode Exit fullscreen mode

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 (0)