DEV Community

Cover image for Crafting Microservices with NodeJS - Or How to Build a Servant from Scratch
Shubham Thakur
Shubham Thakur

Posted on

Crafting Microservices with NodeJS - Or How to Build a Servant from Scratch

Crafting Microservices with NodeJS - Or How to Build a Servant from Scratch

If you're reading this article, I presume that you've been smitten by the microservices charm and you're brave enough to tinker with it. Kudos, my friend. For those who just stumbled upon this article and are wondering, "What the heck is a microservice?" Well, microservices architecture is like having an army of small, efficient minions, each skilled at a specific task, as opposed to having a large, bulky, and clumsy monolith that tries to juggle everything (and often drops the ball).

Alright, enough of chit-chat. Let's roll up our sleeves and start crafting our very own microservice using NodeJS, the hip language that's as cool as the other side of the pillow. We'll be building a simple microservice that accepts a POST request with a JSON body of text and spits out the character count. Revolutionary? Nah. Informative? Absolutely.

1. The Shopping List

To start with, we need to install NodeJS and npm (Node Package Manager). They're like Batman and Robin in the world of JavaScript. If you haven't installed these, the internet is full of tutorials. Pick one and follow it. Now let's get some more tools, because you can't build a house with just a hammer.

  • Express - A minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Basically, the bread and butter of our microservice sandwich.

  • Body-parser - A piece of middleware that helps us process JSON payloads. Think of it as a language interpreter for our service.

To install these dependencies, open your terminal and play the role of a npm magician.

npm install express body-parser --save
Enter fullscreen mode Exit fullscreen mode

2. Setting Up the Boilerplate

We have our tools. Now, let's start putting things together. We'll begin by setting up a simple server. Create a new file called app.js and put the following code in it:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');

app.use(bodyParser.json());

app.listen(3000, () => {
  console.log('Microservice listening on port 3000. Be there or be square!');
});
Enter fullscreen mode Exit fullscreen mode

Run the script using node app.js and if you see the console message, congrats, your server is alive. It doesn't do anything right now, but hey, Rome wasn't built in a day.

3. Building the Microservice - 'The Character Counter'

Let's start putting this microservice together. What we want is a POST endpoint that accepts JSON data and returns the number of characters in the text.

Add the following code to app.js:

app.post('/count', (req, res) => {
  const text = req.body.text;

  if (!text) {
    res.status(400).json({ error: 'No text provided. What do you expect me to count?' });
    return;
  }

  const count = text.length;

  res.status(200).json({ text: `Your text is ${count} characters long. Such a novel you've written there!` });
});
Enter fullscreen mode Exit fullscreen mode

Voila! You have your first microservice. All you need to do now is to start the server using node app.js and send a POST request to http://localhost:3000/count with a JSON body of {"text": "your text here"}. What's that you ask? How to send a POST request? You can use Postman, curl, or any other tool that makes

you feel like a wizard.

4. Pat Yourself on the Back

Well, there you have it. A simple NodeJS microservice that doesn't do much but does it well. So, go ahead, crack open a soda, bask in the glory of your success, and start thinking about the next microservice you want to build. After all, one minion is never enough.

Conclusion

Now that you've dipped your toes in the world of microservices, remember that the concept extends far beyond this simple example. You have databases to connect, authentication to manage, multiple services to orchestrate, and yes, bugs to squash. But hey, every giant leap begins with a small step, and you've just taken yours. Happy coding!

Top comments (0)