How to use Node.js as a simple web server?

Sometimes, we want to use Node.js as a simple web server.

In this article, we’ll look at how to use Node.js as a simple web server.

How to use Node.js as a simple web server?

To use Node.js as a simple web server, we can use the connect and serve-static packages.

To install them, we run

npm install connect serve-static

Then we write the app.js script by writing

const connect = require('connect');
const serveStatic = require('serve-static');

connect()
  .use(serveStatic(__dirname))
  .listen(8080, () => console.log('Server running on 8080...'));

to call connect and use with the static file object returned by serveStatic called with the folder of the current project, which is __dirname.

And then we call listen with the port to listen to requests to and a callback that’s run when the server is running.

Then we run it with node app.js.

Conclusion

To use Node.js as a simple web server, we can use the connect and serve-static packages.