Getting Started with Your First Node.js Application

Getting Started with Your First Node.js Application

This guide is designed for beginners looking to build their first application using Node.js. Node.js is a powerful runtime environment that enables you to execute JavaScript on the server side, opening up a world of possibilities for web development.

Key Concepts

  • Node.js:
    • A JavaScript runtime built on Chrome's V8 engine.
    • Facilitates the development of scalable network applications.
  • HTTP Module:
    • A core module in Node.js that allows for the creation of HTTP server functionalities.

Steps to Create Your First Node.js Application

  1. Setup Node.js Environment:
    • Ensure Node.js is installed on your machine. You can download it from the official website.
  2. Create a New File:
    • Open your text editor and create a new file, for example, app.js.
  3. Run Your Application:
    • Open your terminal or command prompt, navigate to the directory where app.js is located, and execute the following command:
  4. Access Your Application:
    • Open a web browser and go to http://127.0.0.1:3000/. You should see "Hello World" displayed.
node app.js

Write Your First Application:Use the following code to create a basic HTTP server:

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Conclusion

Creating your first Node.js application is a straightforward process. By following the steps outlined in this guide, you can set up a simple HTTP server that responds with a friendly message. This foundational experience paves the way for developing more complex applications using Node.js.

Key Takeaways

  • Node.js allows you to run JavaScript on the server.
  • The HTTP module is essential for creating web servers.
  • You can run a Node.js application via the terminal using the command node filename.js.