I am beginner in the field of node js.No idea how to send simple request from url Like :- http://localhost:9999/xyz/inde.html my file hierarchy is
server.js
xyz
Heads up for anyone attempting to serve static files without Express or any other framework:
There is no benefit to skipping Express, in terms of performance or productivity. The only exception is to gain an understanding of how the server and client communicate with each other. Frameworks like Express abstract away all of those complexities, and beginners may not fully understand how they work.
Here is my approach to serving static files using Node.js only. Actually, the reason I did this is because a coding test I was given stipulated no framework whatsoever.
First, decide what the URL path for those static files should look like. I want mine to be accessible under /assets/
path, such as https://example.com/assets/main.css
, https://example.com/assets/cat.jpg
.
Decide the REGEX for matching those URL. `const assetPattern = /^/assets/[a-zA-Z]+.[a-zA-Z]+/;
The formula above will match urls which contains /assets/[filename].[file extension
.
// ...
const http = require('http')
const server = http.createServer(requestListener).
const path = require('path');
// ...
const requestListener = (req, response) => {
// get the relative url for the request. For example, relative url for a request
// to https://example.com is /.
const { url } = req;
if (url.match(assetPattern)) {
// Inside the project directory, the static files are located under the
// /public/assets directory.
const filePath = `./public/${url}`;
// Get the extension name aka the string after the dot. For example, a url like
// https://example.com/assets/main.css will result in extension name of css.
const extname = String(path.extname(filePath)).toLowerCase();
const mimeTypes = {
'.html': 'text/html',
'.js': 'text/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpg',
'.gif': 'image/gif',
'.svg': 'image/svg+xml',
'.wav': 'audio/wav',
'.mp4': 'video/mp4',
'.woff': 'application/font-woff',
'.ttf': 'application/font-ttf',
'.eot': 'application/vnd.ms-fontobject',
'.otf': 'application/font-otf',
'.wasm': 'application/wasm',
};
const contentType = mimeTypes[extname] || 'application/octet-stream';
staticFileHandler(req, response, filePath, contentType);
}
}
fs
moduleconst fs = require('fs')
// ...
const staticFileHandler = (req, res, filePath, contentType) => {
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500);
res.end(`Sorry, check with the site admin for error: ${err.code}`)
} else {
res.writeHead(200, { 'Content-Type': contentType }); // indicate the request was successful
res.end(content, 'utf-8');
}
}
}