Welcome to the tutorial on getting started with Node.js! If you're new to Node.js or looking to enhance your skills, this guide will help you understand the basics and get you up and running in no time.

What is Node.js?

Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It allows you to run JavaScript outside of a browser, enabling you to build server-side applications, command-line tools, and more.

Features of Node.js

  • Single-threaded: Node.js is single-threaded, meaning it handles requests in a single thread of execution. This can be beneficial for non-blocking I/O operations.
  • Non-blocking I/O: Node.js uses non-blocking I/O operations, which means it can handle many connections simultaneously without waiting for a response from the server.
  • Asynchronous: Node.js is asynchronous, allowing you to perform tasks in the background without blocking the main thread.

Install Node.js

To get started, you'll need to install Node.js on your system. You can download it from the official Node.js website. Once installed, open your terminal or command prompt and run:

node -v

This will display the version of Node.js installed on your system.

Create a Simple Server

Now that you have Node.js installed, let's create a simple server to serve static files.

const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
      if (err) {
        res.writeHead(500);
        return res.end('Server Error');
      }
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(data);
    });
  }
});

server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

Save this code in a file named server.js and run it using the command:

node server.js

Now, open your web browser and navigate to http://localhost:3000. You should see the content of your index.html file.

Learn More

To dive deeper into Node.js, we recommend checking out our Node.js tutorials. These tutorials cover a wide range of topics, from basic concepts to advanced techniques.

Node.js Logo

Happy coding!