To Serve Static Assets Content on NodeJS Server Using ExpressJS Server. NodeJS server is very popular for real-time application development. Using the NodeJS server we can also develop a web application that the application supports on the browser. Recently while learning NodeJS, and from basic I want to serve the assets files (e.g. Stylesheets, CSS […]
NodeJS server is very popular for real-time application development. Using the NodeJS server we can also develop a web application that the application supports on the browser.
Recently while learning NodeJS, and from basic I want to serve the assets files (e.g. Stylesheets, CSS files, Images, or any other file) to my application we have to manage it manually in NodeJS but if we use an Apache server then an Apache server, Apache provides the assets or file serving facility built-in and we just need to follow the directory structure or point to the directory inside the configuration setting. But in NodeJS we have to manage it.
If we do not use ExpressJS which is a popular server library for the NodeJS server, then we have to use the built-in HTTP module to manage the incoming request any kind of request.
With HTTP module we can handle it inside the request handling function, like,
// HTTP Module
const http = require('http');
// To determine the file-type to set the content-type when asset file request received
const mime = require('mime');
// For reading file from the directory
const { readFileSync, existsSync } = require('fs');
const server = http.createServer( (req, res) => {
const url = req.url;
if( url === '/'){
const home = readFileSync(__dirname + '/index.html');
res.end( home );
}else if( url === '/about'){
const about = readFileSync(__dirname + '/about.html');
res.end( about );
}else if( existsSync( __dirname + url ) ){
/**
* Assets request will be handle here.
* First we have to check that if file existsed or not
* If it is a asset file request then we will return the file content
*/
res.writeHead( 200, { 'Content-Type': mime.getType( __dirname + url )}); // mime.getType determines and return the file type
const sourceFile = readFileSync(__dirname + url);
res.end( sourceFile );
}else{
res.writeHead( 404 );
res.end( 'Not Found' );
}
return;
})
server.listen( 5000);
Here, in the above example, we read the request URL and then check into the server folder if is it an asset file request or not by checking whether the file exists or not. If a file exists then we return the content of the file to load the assets for our application. So we have to handle the assets in NodeJS manually.
A second way we can use ExpressJS is a server library for the NodeJS server. ExpressJS provides a method to handle static content or static files easily.
Here, we will see how we can easily handle it and while implementing it I faced the issue regarding the asset URL. So, for clarification, I will explain how it works and how we can set the manual asset URL.
// ExpressJS library load
const express = require('express');
// Created server with ExpressJS Library
const server = express();
// TO read the file as we read the each request from the separate file to handle the each URL request
const { readFileSync } = require('fs');
// express.static is our key to handle the static assets
// Here, I manage the assets files inside the seaprate directory "assets"
/**
* If we use the below way then first argument default value is "/"
* e.g., http://localhost:5000/styles.css
* http://localhost:5000/logo.png
* http://localhost:5000/app.js
*/
server.use( express.static( __dirname + '/assets') );
/**
* If we want our custom asset URL then we have to provide the URL as the first argument
*
* e.g., http://localhost:5000/assets/styles.css
* http://localhost:5000/assets/logo.png
* http://localhost:5000/assets/app.js
*/
server.use( '/assets', express.static( __dirname + '/assets') );
// Server started on the 5000 port
server.listen( 5000);
// Home route or index route request goes here
server.get('/', ( req, res ) => {
res.status( 200 )
.header({ 'Content-Type': 'text/html'})
.send( readFileSync( __dirname + '/index.html') );
})
// About page url goes here
server.get('/about', ( req, res ) => {
res.status( 200 )
.sendFile( __dirname + '/about.html' );
});
// All other request goes here and return 404 page
server.all('*', ( req, res ) => {
res.status( 404 )
.send( readFileSync( __dirname + '/error.html'));
});
Here, I am sharing this example because sometimes we want a custom assets URL to manage our assets on the request then we have to set it as a first argument, and if we will not set then it will take the default value and it is "/" our default root slug and assets will be served from the root slug.