-- then run node to start the node web server:
cd /home/xxx
node simpleServer.js
the code uses async/await to check for the existence of a file.
// using async/await to check for the existance of a file:
const exist = await fs_exists(fs, pathname) ;
if (!exist)
{
// if the file is not found, return 404
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
return;
}
// compared to traditional way of using a callback:
fs.exists(pathname, function (exist)
{
if (!exist)
{
// if the file is not found, return 404
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
return;
}
-----------------
// /home/njs/simpleServer.js
// simpleServer.js - basic web server. Serves back the files requested in
the
// url. use async and await.
// special file name. Shutdown this process.
if (req.url == '/shutdown')
{
webServer.close();
process.exitCode = 1;
process.exit(1);
return;
}
// parse URL
const parsedUrl = url.parse(req.url);
// extract URL path
let pathname = `.${parsedUrl.pathname}`;
// based on the URL path, extract the file extention. e.g. .js, .doc, ...
const ext = path.parse(pathname).ext;
// maps file extention to MIME typere
const map = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.svg': 'image/svg+xml',
'.pdf': 'application/pdf',
'.doc': 'application/msword'
};
const exist = await fs_exists(fs, pathname) ;
if (!exist)
{
// if the file is not found, return 404
res.statusCode = 404;
res.end(`File ${pathname} not found!`);
return;
}
// if is a directory search for index file matching the extention
if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext;
// read file from file system
fs.readFile(pathname, function (err, data)
{
if (err)
{
res.statusCode = 500;
res.end(`Error getting the file: ${err}.`);
} else
{
// if the file is found, set Content-type and send data
res.setHeader('Content-type', map[ext] || 'text/plain');
res.end(data);
}
});
This mailing list archive is Copyright 1997-2024 by midrange.com and David Gibbs as a compilation work. Use of the archive is restricted to research of a business or technical nature. Any other uses are prohibited. Full details are available on our policy page. If you have questions about this, please contact
[javascript protected email address].
Operating expenses for this site are earned using the Amazon Associate program and Google Adsense.