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
I don't agree with the assertion in the accepted answer:
"It's ridiculous to attempt to create a node application without npm dependencies"
as having zero dependencies allows you to deploy an app to a system that runs node by just copying the javascript file(s), and without running npm install
.
An example of when I found this useful in real life was writing a public API to compute the amount of income tax a business needs to withold from an employee's pay. You can read all about this fascinating topic here but in essence I had an api that was passed a gross income and returned how that gross income should be split between net income and tax.
I did this with one solitary index.js file, no package.json, and need to npm install
:
index.js:
http = require('http');
url = require('url');
const port = 80; // make this a number over 1024 if you want to run `node` not run `sudo node`
const debug = true;
const httpServer = http.createServer((request, response) => {
response.setHeader('Content-Type', 'application/json');
const parsedUrl = url.parse(request.url, true);
let pathName = parsedUrl.pathname;
if (pathName==='/favicon.ico') {
// chrome calls this to get an icon to display in the tab. I want to ignore these request. They only happen when testing in a browser,
// not when this api is called in production by a non-browser.
if (debug) console.log('Browser requested favicon.ico')
response.end();
} else {
if (debug) console.log('Request on path ' + pathName);
const elements = pathName.split('/');
if (elements.length == 3 && elements[0] === '' && elements[1]==='witholdcalc') {
const grossString = elements[2];
const gross = Number.parseInt(grossString);
if (isNaN(gross)) {
response.writeHead(400).end(JSON.stringify({error:'Gross salary must be an integer. found: ' + grossString}));
} else {
/*
* The computation of the amount to withold is more complicated that this, but it could still be hard coded here:
* For simplicity, I will compute in one line:
*/
const withold = Math.floor((gross<1000)?0:((gross-1000)*.2));
response.writeHead(200).end(JSON.stringify({net: (gross-withold), withold: withold, elements:(debug?elements:undefined)}));
}
} else {
if (debug) console.log('Invalid path was: ' + pathName,elements);
response.writeHead(404).end();
}
}
});
httpServer.listen(port), () => {
console.log(`PAYG listening at http://localhost:${port}`)
}
I then could execute sudo node install.js
on my linux computer, and in a browser, hit http://localhost/witholdcalc/6000
, and it would return {"net":5000,"withold":1000} when debug is set to false.