Build an Easy NodeJs App Without Frameworks

In a wild coding adventure, we ditched the frameworks and built a Node.js REST API straight from the heart. No Express, no fastify. Just pure Node.js magic! We cruised through creating endpoints, handling requests, and even added some spice with dynamic routing. Keep it lean, keep it mean. Node.js at its finest! πŸš€


Introduction πŸš€

In this tutorial, we’ll explore how to construct a REST API using Node.js without relying on external frameworks like Express. Let’s dive in!


Preparing Your Environment πŸ–₯️

Before we begin, ensure that Node.js is installed on your system. You can verify its installation and version using the command prompt:

node -v
npm -v

Create a new folder for your project and open it with your preferred code editor.


Initializing Your Application πŸ“

Initialize your Node.js application by running the npm init command in your terminal. This will prompt you to provide information about your project, such as the name, version, and description.

npm init

Follow the prompts to complete the initialization process. This will generate a package.json file, which serves as the configuration for your application.


Creating the Main Entry File πŸ“

Next, create your main entry file, typically named index.js. This file will serve as the starting point for your application.

// index.js

console.log("Hello, world!");

Save the file and run it using Node.js to ensure everything is set up correctly:

node index.js

You should see "Hello, world!" printed in your terminal.


Setting Up a Basic Server 🌐

Now, let’s create a basic server using Node.js’s built-in modules such as http, url, and fs.

// index.js

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}/`);
});

Run the server by executing node index.js. You should see the message "Server running at http://127.0.0.1:3000/" in your terminal.


Handling Endpoints πŸ›£οΈ

Endpoints are different routes that clients can request from the server. Let’s define some basic endpoints for our API.

// index.js

const http = require('http');

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

const server = http.createServer((req, res) => {
  const { method, url } = req;

  if (url === '/') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Welcome to the landing page!\n');
  } else if (url === '/about') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('About page\n');
  } else if (url === '/adopt') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Adopt a puppy!\n');
  } else {
    res.statusCode = 404;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Page not found\n');
  }
});

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

Run the server again and navigate to different endpoints (e.g., http://127.0.0.1:3000/about) to see the responses.


Optimizing Your Code with DRY Principles 🌟

DRY (Don’t Repeat Yourself) is a fundamental principle in software development. Let’s refactor our code to eliminate duplication.

// index.js

const http = require('http');

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

const server = http.createServer((req, res) => {
  const { method, url } = req;

  const endpoints = {
    '/': 'Welcome to the landing page!\n',
    '/about': 'About page\n',
    '/adopt': 'Adopt a puppy!\n',
  };

  const defaultResponse = 'Page not found\n';

  res.statusCode = endpoints[url] ? 200 : 404;
  res.setHeader('Content-Type', 'text/plain');
  res.end(endpoints[url] || defaultResponse);
});

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

By using an object to map endpoints to responses, we’ve made our code more concise and maintainable.


Conclusion πŸŽ‰

In this tutorial, we’ve learned how to build a simple REST API using Node.js without relying on external frameworks. By understanding the core modules of Node.js, you can create lightweight and efficient web applications.


Key Takeaways πŸ“Œ

  • Node.js provides built-in modules for creating web servers and handling HTTP requests.
  • Endpoints are different routes that clients can request from the server.
  • DRY (Don’t Repeat Yourself) is a fundamental principle in software development, encouraging code reuse and maintainability.

FAQ ❓

Q: Can I use Node.js with external frameworks like Express?
A: Yes, Node.js can be used with external frameworks like Express to simplify the process of building web applications.

Q: What are some common use cases for Node.js?
A: Node.js is commonly used for building web servers, real-time applications, and microservices.

Q: Is Node.js suitable for large-scale applications?
A: While Node.js can be used for large-scale applications, its single-threaded, event-driven architecture may not be ideal for CPU-intensive tasks.


Thank you for joining us on this journey of exploring Node.js! Happy coding! πŸš€

About the Author

The Zuri Team
44.2K subscribers

About the Channel:

Unlock your Brilliance with our hands-on beginner and expert training. Zuri Team has been immensely successful in creating a global network of a highly adept intelligent workforce that can help your company achieve their mission-critical projects and goals
Share the Post:
en_GBEN_GB