loading...
Cover image for A Simple Introduction to NodeJS.

A Simple Introduction to NodeJS.

bilianemoreira profile image Biliane Moreira ・5 min read

What is NodeJS for?

For those who don't know, NodeJS is open-source created by Ryan Dahl that allows us to use Javascript so that we can create scripts on the command line and communicate with the server in order to produce dynamic content for our applications before everything is done. rendered to the user.

ASome main features of NodeJS are:

  • We do not handle end-user events;
  • We can make routes and integrations in the Backend using Javascript.

NPM

At Node, we usually use a package manager known as NPM (Node Package Manager), which hosts thousands of free packages created by various developers (you can also create packages and distribute through them). A NodeJS package contains all the files we need to start with the node. We can also manage versions and dependencies that are used to execute a project/application.

Yarn

Yarn is another package manager that has been gaining great repercussions for making the management process even easier because it stores a cache of packages that have already been downloaded making it faster than NPM and with more advanced technologies.

Features in NodeJS

  • Event-loop architecture (based on events);
  • Call Stack - uses a stack of events where whenever a function is executed, it enters the stack, which executes only one thing at a time;
  • Initially, Single thread (only one processor core), when using V8 (Google Engine used to run the Node);
  • Uses the C ++ libuv (which allows you to use more processor threads and make the Call Stack faster);
  • Non-blocking I / O architecture - which transmits non-blocking input and output - a request that returns a more summarized listing and not all at once, and can be listed in parts (important for real-time applications, eg in chats ).

The Call stack receives a stack with functions that are in the event loop, the function that comes later is the first to be processed, known as * Last in, First out * (Lifo).

Frameworks to NodeJS

There are many Frameworks used with NodeJS that were created to facilitate productivity and scalability, when for example, we can use specific treatments for HTTP methods (GET, POST, DELETE, PUT) and also separate and handle route and dynamic responses. Some of them are:

  • ExpressJS
  • AdonisJS
  • NestJS
  • Meteor
  • SailsJS
  • Loopback
  • Nest Js, etc.

ExpressJS

I will give a summary of the use of the ExpressJS Framework, as it is what I know and which I have now learned to use.

Some of the features of ExpressJS:

  • It has an open structure;
  • Used in microservices (divide the application);
  • Use handlers for different HTTP verbs and different routes (URL);
  • Add middleware, which adds more requests at any point and which solves many web development problems.

Using API - REST (one of the ExpressJS utilities)

An API (Application Programming Interface), is a set of routines and standards established and documents by one type of application so that another application can use its functionality without needing to know all the details. It is the interoperability of applications.

The REST (Representational State Transfer), on the other hand, are principles that allow the creation of a project with well-defined interfaces and that allow applications to communicate with each other.

Joining the REST API we have a set of HTTP methods that request information from the server through HTTP protocol and ExpressJS that allows us to use these methods.

The REST API works as follows in the request and response flow:

  • Request made for a client
  • The response returned through a data structure (array type)
  • The customer receives responses and processes results.

HTTP Methods:

We use the following HTTP methods when creating routes:

  • GET - http://myapi.com/users (seek information within the backend);
  • POST - http://myapi.com/users (to create some information on the backend);
  • PUT/PATCH - http://myapi.com/users/1 (to change some information on the backend). Note: PUT is used for various information and PATCH for specific information.
  • DELETE - http://myapi.com/users/1 (to delete information on the backend) Note: The above users are called resources or routes. The '1' are parameters passed in the PUT or DELETE.

Examples of pieces of code used in the app.js file in a node application with Express and REST:

//GET
app.get("/repositories", (request, response) => {
  const { title } = request.query;

  const results = title 
  ? repositories.filter(repo => repo.title === title) 
  : repositories;

  return response.json(results);
});

//POST
app.post("/repositories", (request, response) => {
  const { title, url, techs } = request.body;

  const repository = { id: uuid(), likes: 0, techs, title, url };

  repositories.push(repository);

  return response.json(repository);
});

//PUT
app.put("/repositories/:id", (request, response) => {
  const { id } = request.params;
  const { title, url, techs } = request.body;

  const repositoryIndex = repositories.findIndex(repo => repo.id === id);

  if (repositoryIndex < 0) { 
      return response.status(400).json({ error: 'Repository not found'});
  }

  const { likes } = repositories[repositoryIndex]

  const repository = {
      id, 
      title,
      url,
      techs,
      likes
  };

  repositories[repositoryIndex] = repository;

  return response.json(repository);
});

//DELETE
app.delete("/repositories/:id", (request, response) => {
  const { id } = request.params;

    const repositoryIndex = repositories.findIndex(repo => repo.id === id);

    if (repositoryIndex < 0) { 
        return response.status(400).json({ error: 'Project not found'});
    }

    repositories.splice(repositoryIndex, 1);

    return response.status(204).send();
});

Note: the parameter: id must be used when using the PUT method (since the change is only in one file) and in the DELETE method (as we generally do not want to delete all files)

ex:

app.put('/projects/:id', (request, response) => {
    return response.json([
        'project 4',
        'project 2',
        'project 3'

    ]);
});

Testing routes

I generally use an open-source tool to test routes made with REST called Insomnia

Main types of parameters - HTTP Method

Query Params

Query params receive the request data as a parameter in the URL, it can contain 1 or more parameters.

Route params

Receive the requested data on the route, it is the best way to search for something, delete or update by ID, for example:

GET http://myapi.com/animes/1
DELETE http://myapi.com/animes/1
PUT http://myapi.com/animes/1

Request Body

It is used for the rest of the requisitions, more precisely the content when creating or editing a resource with POST create (through JSON) eg: Frontend registration form

This can be done by Insomnia in the * Body> JSON tab and enter the following code: *

{
    "title": "App React Native",
    "owner": "Biliane Moreira"
}

To obtain the body data of the request, we can access it with the following piece of code in POST:

app.post('/projects', (request, response) => {
const body = request.body;

    console.log(body);

app.post('/projects', (request, response) => {
    const { title, body } = request.body;

    console.log(title);
    console.log(body);

Note: By default, Express does not interpret what we send to it in JSON.

So we must add information to our code so that Express understands that our API will receive information in the JSON format, after "const app = express ();" and always before routes.

app.use(express.json());

HTTP codes

It is interesting that a response is placed in the code when the user's request is not fulfilling or is not found, return an error or success message to the user if his request is found. 3 digit number that identifies the status of that response to the request, as in the example below:

if (repositoryIndex < 0) { 
    return response.status(400).json({ error: 'Repository not found'});
  }

The principals errors code is:

  • 1xx: is informative;
  • 2xx: Success (200: success and 201: created);
  • 3xx: Redirection (301 moved permanently and 302 moved):
  • 4xx: Client Error: (400: Bad request, 401: unauthorized, 404: Not found);
  • 5xx upwards are Server Error (500: Internal server error).



If you want to learn more about NodeJS, I advise you to read the guides here.

There are also great courses at Udemy, like Maximilian's course.



See you in the next post!

Discussion

pic
Editor guide