Need a backend for your web? Start with Node.js

I’ve been working with NodeJS lately for a Single Page Application (SPA) backend, for authentication using JSON Web Tokens (JWT), connecting to third-party services, exposing REST APIs, creating unit tests, and developing Command Line Interfaces (CLI) to process folders and files. I think it’s time for me to talk about NodeJS.

If you want to know what Node.js is, what I like about it, what is good for or you are curious to know about the basics of an API, keep reading and I will show you how to run a web service that exposes an API, and how to create some unit tests to ensure your application core business is working.

What is Node.js?

Node.js is an open-source, cross-platform, back-end, JavaScript runtime environment that executes JavaScript code outside a web browser. Node.js lets developers use JavaScript to write command line tools and for server-side scripting — running scripts server-side to produce dynamic web page content before the page is sent to the user’s web browser.

What Wikipedia is saying is Node.js is just javascript running on your computer instead of a web browser. It can run in any OS, in a docker container, even in raspberry pi, and can be used to create any tool, like a terminal command to copy files or create directories for example. Most of the web browsers and Nodejs, interpret javascript using the V8 engine, Google’s open-source, high-performance engine, that is improving every year.

Why is used?

As you can imagine, Node.js is efficient and lightweight and is able to do this using an event-driven, non-blocking I/O model. Is fast and is getting faster every year. It’s easy to catch up, you know javascript? Boom! you already familiar with the language, an excellent tool for a front-end web developer to use to connect your database and expose an API to be consumed with javascript.

Where do we start?

I was thinking of talking about some key features or the latest V8 engine updates, but this article would be too large, since I like to code, I prefer to jump directly to code and create our API.

Installing necessary tools

Code editor of preference, mine is Visual Studio Code, is lightweight, works with any coding language. I’ve used it for Golang, java, python, HTML, javascript, and Arduino all in the same code VSCode workspace, it does the magic!

We’ll need Node.js, so go ahead and install it. And, if we are talking about Node.js we will use some dependencies (third-party libraries), there is where npm will help manage that, run builds, test, and more. The best of npm is that it comes with Node.js installation, so no further steps are required.

Let’s code

I like to think of my how-to articles as a client requirement, in this case, the requirement would be; the ability to create articles, store them, retrieve, update and delete articles.

To start we need to open a terminal and go to the root folder of your project. If you are using VSCode, you can import the folder to your workspace and open the VSCode terminal by pressing “ctrl+`” (it will open the terminal in your project folder).

If you are starting from my GitHub project you can jump directly typescript initialization, but if you want to know how to create the project from the scratch keep reading.

Next, initialize it as an npm project. Here we are configuring our project.json by answering some questions displayed in your terminal.

npm init

Now we have the npm project configure, let’s install dependencies and write the necessary code for our application, we will be using typescript to create a web service with the help of Express.js, type these two commands in the terminal.

npm install -D typescript tslint @types/express
npm install -S express uuid

The first command has “-D” property used to install development dependencies, which means these dependencies are used only during development and won’t be compiled in the final .js file. The second command uses “-S” property, and is used to save the dependency in the project.json file.

Or if you download the project you can simply execute:

npm install

And will install all the dependencies defined in the project package.json file.

Now we need to configure the project to say, Hey! this will be written in typescript.

tsc --init

This will generate a default configuration file called tsconfig.json, we need to change some properties, like “target ”and specify what version of ECMAScript we are going to use, in our case “ES2020”. We also need to add “outDir”, so the .js file compiled is inside our distribution folder “dist”, so we can add the ignore in our .gitignore file if you are using git.

This is how the tsconfig.json file should look like:

{
“compilerOptions”: { /* Visit https://aka.ms/tsconfig.json to read more about this file */
“target”: “ES2020”,
“module”: “commonjs”,
“outDir”: “dist”,
“strict”: true,
“skipLibCheck”: true,
"strictNullChecks": false,
“forceConsistentCasingInFileNames”: true
}
}

Now the project is configured, we are able to expose a basic API to store articles in a memory database. I used a Map() to keep it simple, but you should connect a database instead.

Let’s look at app.ts, I leave a bunch of comments to explain the process, check it out here -> Github/Gueka/nodejs-examples

We need 2 files, the first one where I will define my API methods (api/src/app.ts), and the other where I will store the article objects (api/src/service/store.ts).

To create and expose our API, we are using a famous Node.js library called Express.js. The app object conventionally denotes the Express application. Create it by calling the top-level express() function exported by the Express module imported.

We are using the app object to expose four basic CRUD functions to persist (persist is a very strong word for this example) in our store. What these CRUD functions mean a read, an update, a create, and delete operations.

How do we initialize our app? Run this command from the /api folder.

npm start

If you are familiar with Postman, an application to execute REST calls, you can import the postman_collection.json file found in the docs folder of the project and test your application behavior right away.

Or you can use your terminal and use a CLI tool called curl if you are familiar with it.

curl http://localhost:3000/ping

Testing

Every application must have unit tests, so I added some basic tests to cover the business logic, ensuring a proper behavior for each function exposed.

What are Mocha and Chai?

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases.

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.

To put it short Mocha is a framework that makes testing simple with readable code and Chai allows you to assert or validate data, so when you call a rest API you can validate the response. As you can see, mocha and chai are like bread and butter. Here you can find more information about Mocha and Chai.

Check the test code of the project (api/test/app.spec.ts). Even if it’s the first time you see a Mocha test, go ahead and read It, and find the beauty of Mocha, it makes the code self-explanatory, making the framework straight forward to use it.

By having unit tests, every time you compile the typescript code it will run the test to make sure your application runs as it should.

What dependencies did I need to create a unit test? Here you have the commands I used.

npm install chai mocha ts-node @types/chai @types/mocha chai-http @types/chai-http --save-dev

Conclusion

What I liked the most about Node.js is its simplicity, easy to learn if you come from an Angular or a React background, it shrinks the gap for front-enders to start coding back-ends by giving Object Oriented capabilities to a very known program language and make it easier for javascript developers to create interesting ideas.

Node.js has an extensive community rapidly growing that supports the language by creating practical libraries to make coding simpler and helping new developers.

We’ll get deeper into the rabbit hole, there is a lot to talk about Node.js, design patterns, protocols, systems, testing, and more, but I hope this introduction to Express.js and typescript give you a push to start coding and understand a bit more about backend technologies.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Marco Capo

I’m a senior software engineer working in technology development for 12+ years from marketing, videogames and microservices for big companies