How to use routes with serve-static files in Node.js ?
Last Updated :
04 Mar, 2022
The purpose of this article is to learn how to use routes to serve static files in Node.js, it has an inbuilt HTTP module to transfer data over the HyperText Transfer Protocol (HTTP) which supports various features that were earlier difficult to use. With the help of the functionality provided by this module complete reconstruction of the document from the sub documents(text, layout description, images, videos, scripts, etc.) is done.
Setting Routes for different URL’s:
app.js
const http = require( 'http' );
const port = 3000;
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
if (url === "/" )
{
res.end( "Path /" );
}
else if (url === "/about" )
{
res.end( "Path /about" );
}
else
{
res.end( "Path not found" );
}
console.log( "Url entered " +url);
});
server.listen(port, () => {
console.log(`Server running at http:
});
|
Output:
Serving Static Files using HTTP module :
App.js
const http = require( 'http' );
const fs = require( "fs" );
const port = 3000;
function readAndServe(path, res)
{
fs.readFile(path, function (err, data)
{
console.log(data);
res.end(data);
})
}
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
if (url === "/" )
{
readAndServe( "./index.html" ,res)
}
else if (url === "/about" )
{
readAndServe( "./about.html" ,res)
}
else
{
res.end( "Path not found" );
}
});
server.listen(port, () => {
console.log(`Server running at http:
});
|
index.html
<!DOCTYPE html>
<!DOCTYPE html>
< html >
< head >
< title >index</ title >
</ head >
< body >
< h2 >Welcome To GeeksForGeeks</ h2 >
< p >This is Index file</ p >
< p >< a href = "/about" >
Click to go to About Page
</ a >
</ p >
</ body >
</ html >
|
about.html
<!DOCTYPE html>
< html >
< head >
< title >About</ title >
</ head >
< body >
< h2 >Welcome To About Page</ h2 >
< p >< a href = "/" >
Click to go to index
</ a >
</ p >
</ body >
</ html >
|
Output : The static files specified for different paths will be served accordingly.
Share your thoughts in the comments
Please Login to comment...