Access External CSS or JS on Local Machine Without Express for Node.js
Using any web development framework for any programming languages is fast. When
creating a website with node, we can also use one of the web framework,
Express.js. We can use middleware app.use to link CSS or JS files in the project
directory.
Just out of curiosity, I want to find out how to do the same without using any
framework. Here is a way how.
Modules
I use only the node's budilt-in modules, http and fs modules.
Logic
- Use http module to create a server.
- Use fs. the file system, to read html, css, and js files.
- the local css or js file link will send request to the node server, so we need to use these request URLs to serve corresponding files to the client.
Example Code
In this example, css and js files are located in the same folder as the htnl file. We create a variable reqUrl to send corresponding files. We use the if(data) to check if any data after reading files are not undefined, which happens when there is no such file to read.
server.js
const http = require('http');
const fs = require('fs');
const port = 3000;
const server = http.createServer((req,res)=>{
let reqUrl = "." + req.url;
fs.readFile(reqUrl,(err,data)=>{
if(data){
res.write(data);
res.end();
};
});
}).listen(port);
console.log("listening on " + port)
Comments
Post a Comment