How to Build a Node.js App from Scratch

Node.js is an open-source, cross-platform JavaScript runtime environment that enables developers to build scalable, high-performance web applications. With its easy-to-use API, event-driven architecture, and robust package ecosystem, Node.js has become a popular choice for building server-side applications.

In this article, we’ll walk you through the steps to build a Node.js app from scratch. Whether you’re a seasoned developer or just getting started with Node.js, this guide will help you create a simple web application and gain a better understanding of how Node.js works.

Introduction

Node.js is a powerful runtime environment for building scalable and performant web applications. It allows developers to use JavaScript on both the client and server sides, making it easier to build full-stack applications with a consistent language and programming model.

In this article, we’ll focus on building a simple Node.js app that demonstrates the basic concepts and features of the platform. We’ll use the popular Express framework to build a web server, handle HTTP requests and responses, and build a RESTful API for interacting with data.

Prerequisites

Before we get started, you’ll need to have some basic knowledge of JavaScript and web development concepts like HTTP, HTML, and CSS. You’ll also need to have Node.js installed on your computer.

If you haven’t installed Node.js yet, you can download the latest version from the official Node.js website. Once you’ve installed Node.js, you should be able to run the node command in your terminal or command prompt.

Setting up your Node.js development environment

To get started with building a Node.js app, you’ll need to set up your development environment. This involves installing the necessary tools and libraries, and configuring your project to use them.

Here are the steps you’ll need to follow:

Step 1: Choose an IDE or text editor. There are many popular options for editing JavaScript code, including Visual Studio Code, Sublime Text, and Atom. Choose the one that you’re most comfortable with and install it on your computer.

Step 2: Create a new directory for your project. Open your terminal or command prompt and navigate to the directory where you want to create your project. Then, run the following command to create a new directory:

mkdir my-node-app

Step 3: Initialize your Node.js project. Inside the new directory, run the following command to create a new package.json file:

npm init -y

This command will prompt you to enter some basic information about your project, such as its name, version, description, and author. You can accept the defaults for most of these prompts, but make sure to enter a meaningful name for your project.The package.json file is an important configuration file that defines the dependencies and scripts for your project. It will be used by npm (the Node.js package manager) to install and manage your project’s dependencies.

Creating a new Node.js project

Now that you’ve set up your development environment, it’s time to create a new Node.js project. This involves installing the necessary dependencies and configuring your project to use them.

Here are the steps you’ll need to follow:

Step 1: Install the Express framework. Express is a popular framework for building web applications with Node.js. It provides a simple and flexible API for handling HTTP requests and responses, and makes it easy to build a RESTful API. To install Express, run the following command in your terminal or command prompt:

npm install express

Step 2: Install other dependencies. In addition to Express, we’ll be using a few other libraries to build our app. Run the following command to install them:

npm install ejs mongoose body-parser

ejs is a template engine that allows us to build dynamic web pages with JavaScript.

mongoose is an Object Data Modeling (ODM) library for MongoDB that makes it easy to work with data in a Node.js app.

body-parser is a middleware that parses incoming HTTP request bodies and makes them available in a JavaScript object format.

Installing and configuring Express

Now that we have our project set up and our dependencies installed, let’s start building our app with Express.

Step 1: Create a new file called index.js in your project directory.

Step 2: Open index.js in your text editor and add the following code:

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`);
});

This code sets up a new Express app, listens on port 3000 for incoming requests, and sends a “Hello World!” response when someone visits the root URL.

Step 3: Run the following command to start your app:

node index.js

This should start your app and output the message “App listening at http://localhost:3000” in your console.

Open your web browser and visit http://localhost:3000. You should see the “Hello World!” message displayed in your browser.

Creating a simple web server

Now that we have a basic Express app up and running, let’s build a simple web server that can serve static files and handle HTTP requests.

Step 1: Create a new directory called public in your project directory. This directory will contain our static files (like HTML, CSS, and JavaScript).

Step 2: Create a new file called index.html in the public directory and add the following HTML code:

<!DOCTYPE html>
<html>
<head>
  <title>My Node.js App</title>
</head>
<body>
  <h1>Welcome to my Node.js App!</h1>
</body>
</html>

Step 3: Modify your index.js file to serve static files from the public directory. Add the following code:

app.use(express.static('public'));

This code tells Express to serve static files from the public directory.

Step 4: Run the following command to restart your app:

node index.js

Open your web browser and visit http://localhost:3000. You should now see the “Welcome to my Node.js App!” message displayed in your browser.

Handling HTTP requests and responses

Now that we have a basic web server set up, let’s learn how to handle HTTP requests and responses in our app.

Step 1: Modify your index.js file to handle a GET request for the root URL. Replace the existing app.get() code with the following code:

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

This code tells Express to send the index.html file when someone visits the root URL.

Step 2: Add a new route to handle a GET request for a “contact” page. Add the following code:

app.get('/contact', (req, res) => {
  res.send('Contact us at contact@example.com');
});

This code tells Express to send a “Contact us” message when someone visits the /contact" URL.

Step 3: Add a new route to handle a POST request to submit a contact form. Add the following code:

app.post('/contact', (req, res) => {
  // Handle form submission
});

This code tells Express to handle a POST request to the /contact URL.

Step 4: Install and configure the body-parser middleware to parse incoming form data. Add the following code:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

This code tells Express to use the body-parser middleware to parse incoming form data.

Step 5: Handle the form submission in the /contact route. Add the following code:

app.post('/contact', (req, res) => {
  const name = req.body.name;
  const email = req.body.email;
  const message = req.body.message;

  // Do something with the form data

  res.send('Thanks for contacting us!');
});

This code retrieves the form data from the HTTP request, does something with it (like save it to a database or send it in an email), and sends a “Thanks for contacting us!” message in response.

Connecting to a database

Now that we know how to handle HTTP requests and responses, let’s learn how to connect to a database and work with data in our app.

Step 1: Install and configure the mongoose library to connect to a MongoDB database. Add the following code:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myapp', { useNewUrlParser: true });

This code tells mongoose to connect to a MongoDB database called myapp running on localhost.

Step 2: Define a new Contact schema to represent our contact form data. Add the following code:

const contactSchema = new mongoose.Schema({
  name: String,
  email: String,
  message: String
});

This code defines a new Contact schema with three fields: name, email, and message.

Step 3: Define a new Contact model to work with our database. Add the following code:

const Contact = mongoose.model('Contact', contactSchema);

This code defines a new Contact model that uses the contactSchema schema.

Step 4: Modify the /contact route to save the form data to the database. Add the following code:

app.post('/contact', (req, res) => {
  const name = req.body.name;
  const email = req.body.email;
  const message = req.body.message;

  const contact = new Contact({
    name: name,
    email: email,
    message: message
  });

  contact.save((err) => {
    if (err) {
      console.error(err);
      res.send('Error saving contact form data');
    } else {
      res.send('Thanks for contacting us!');
   
});
});

This code creates a new `Contact` object with the form data, saves it to the database using the `save()` method, and sends an appropriate response depending on whether the save was successful or not.

Conclusion

In this article, we’ve learned how to build a Node.js app from scratch using the Express framework and connect it to a MongoDB database using the Mongoose library. We’ve covered the basics of handling HTTP requests and responses, parsing form data, and working with data in a database. With these skills, you can build powerful and scalable web applications using Node.js.

FAQs

What is Node.js?

Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to build server-side applications using JavaScript.

What is Express?

What is Node.js?
Node.js is an open-source, cross-platform JavaScript runtime environment that allows developers to build server-side applications using JavaScript.

What is MongoDB?

MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents.

What is Mongoose?

Mongoose is an Object Data Modeling (ODM) library for Node.js that provides a schema-based solution to model your application data.

Is Node.js suitable for building large-scale web applications?

Yes, Node.js is suitable for building large-scale web applications due to its event-driven architecture, which allows for high concurrency and scalability.

Avatar of suneel kumar

I am a software development engineer with two years of experience, and I have a passion for creating coding blogs that provide valuable insights to fellow developers. In my free time, I enjoy reading books and articles that help me enhance my skills and produce high-quality content for my readers.

Sharing Is Caring:

1 thought on “How to Build a Node.js App from Scratch”

Leave a Comment