Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *