Simple Node.js server for static and dynamic content
This is a simple application written in Node.js without using any frameworks to serve static and dynamic content.
-
Download the
index.jsfile and place it in its own folder such asminimal-dynamic-http-server/ -
Import the server in your code
const server = require('./minimal-dynamic-http-server'); -
If serving dynamic content, set the allowed paths and corresponding listeners by calling
server.setAllowedPaths()method.const paths = { '/api/abc': abcHandler, '/api/def': defHandler }; server.setAllowedPaths(paths); -
Write the request handlers
const abcHandler = (responseData, callback) => { // Code goes here... //Finally call the callback function with statusCode as the first argument and response as the second argument. callback(200, 'This is a test response'); } const defHandler = (responseData, callback) => { // Code goes here... } -
Start the server
server.init(); // This will start the server on port 3000or, explictly specify the port
server.init(3500); //This will start the server on port 3500
Example: http://localhost:3000/public/index.html
This will display /public/index.html page
Based on the sample path shown above
http://localhost:3000/api/abc
will display "This is a test response"
const server = require('./minimal-dynamic-http-server');
const paths = {
'/api/abc': abcHandler,
'/api/def': defHandler
};
server.setAllowedPaths(paths);
const abcHandler = (responseData, callback) => {
// Code goes here...
//Finally call the callback function with statusCode as the first argument and response as the second argument.
callback(200, '{"foo":"bar"}');
}
const defHandler = (responseData, callback) => {
// Code goes here...
callback(200, '{"message":"Have a nice day!"}');
}
server.init(3500);