To serve a static application using Node.js, you need to install and set up a module called express. Express is a minimal, open-source and flexible Node.js web application framework that provides robust features for web and mobile applications.
Below are the step by step guide on how to serve a static application with Node.js.
1. Install Node.js and npm(Node Package Manager) if you haven’t already.
1. Next, you’ll need to install the Express module. Create a fresh directory for your application first. Then via the terminal navigate inside the directory and run the following command to initialize npm. \`\`\` npm init —yes \`\`\` The above command will create a file “package.json” in the current directory.
1. Then install express using the command. \`\`\` npm install express —save \`\`\` This command installs Express and saves it as a dependency in your package.json file.
1. Create an “app.js” file and open it in an editor(you can use any text editor).
1. Now let’s configure our express application to serve static files. Write the below code in the app.js. \`\`\`js var express = require(‘express’); var app = express();
app.use(express.static(‘public’)); //public is directory name where our static files reside app.listen(3000, function () { console.log(‘App is listening on port 3000!’); }); \`\`\` In the above code, express.static(‘public’) is a built-in middleware function in Express. It serves static files and the ‘public’ is the folder from where it will serve the static files like html, css, javascripts, and images etc.1. You can store your HTML, CSS, JavaScript, images and any other static files in the public directory, and Express.js will serve them to the client whenever they are requested.
1. Run “node app.js” from the terminal to start your application.
1. If you goto “http://localhost:3000” you can see your app running. For example, If you’ve an index.html file in the public directory, you would see its content.
Note: Express.js allows you to manage everything, from routes, to handling requests and views. This method of serving static files is suitable for small projects or for quick prototyping. If you are dealing with a large application, it is suggested to use a reliable web server such as Nginx or Apache.