Node.js Series: Smoothly running it

Hey there!

[Versão em Português]

This is part 5 of my Node.js series, make sure you checkout the previous posts!

So far in the series we have determined that there are a lot of advantages migrating to Node.js, from programmer’s team ease of adoption to performance, but it does need a few tools though.

When running your code directly from the node or npm executable, as it happens in any other languages, errors will occur, so you do not want your services braking down every time someone forgets to treat some exception. You will also like to continuously deliver code updates without clients experiencing downtime or performance degrading.

To achieve this you should probably be checking PM2 out, from Keymetrics.

This tool will not only keep your code running, but it also gives you strong professional tools for monitoring, managing and even debugging your running code.

If you already have Node.js installed, all you need to do is run this on your console:

npm install pm2 -g

Once you have it, it is easy to run you first code, if you have a javascript file that runs with node, let’s say it is called myservice.js, you can start it by running the code below. For this example I am using the code I posted previously, so go check it out!

pm2 start myservice.js

If your console returns something like this, you are good to go:

[PM2] Starting /myservice.js in fork_mode (1 instance)
[PM2] Done.
⇆  PM2+ activated | Web: https://app.pm2.io/#/r/MY_ID | Server: vrsbrazil | Conn: Axon
PM2+ on-premise link: root.keymetrics.io
┌───────────┬────┬──────┬──────┬────────┬─────────┬────────┬─────┬───────────┬──────────┬──────────┐
│ App name  │ id │ mode │ pid  │ status │ restart │ uptime │ cpu │ mem       │ user     │ watching │
├───────────┼────┼──────┼──────┼────────┼─────────┼────────┼─────┼───────────┼──────────┼──────────┤
│ myservice │ 0  │ fork │ 7398 │ online │ 0       │ 0s     │ 0%  │ 12.8 MB   │ vrsbrazil│ disabled │
└───────────┴────┴──────┴──────┴────────┴─────────┴────────┴─────┴───────────┴──────────┴──────────┘
 Use `pm2 show ` to get more details about an app

So this is the part where it gets interesting. If you checkout line 3, you will see an URL, the ID here is obviously changed but once you run it on your machine and reach out to this link, you will get to the cloud monitoring page, and it looks like this:

Captura de tela de 2018-08-02 11-43-21

As you can see this is obviously a paid feature, but it can really level up your game. If you have up to 4 processes you may use the free version and there is actually a lot to it, the real time monitoring it offers is quite useful, but there are a lot of features you may get with the paid one.

Captura de tela de 2018-08-02 11-59-15

Back on the console, like I mentioned in the beginning, you will want to have your service fault proof and this is one of the pre-built features, in case your code fails, PM2 will automatically start restart it for you. Of course there needs to be a way you make sure your processes will start automatically in case you need to restart your server and to do that all you need to do is run this at your console:

pm2 startup

The console you return the next command you need to run in order to enable it to start on boot, in my case, this is what I got:

[PM2] Init System found: systemd
[PM2] To setup the Startup Script, copy/paste the following command:
sudo env PATH=$PATH:/usr/bin /home/vrsbrazil/.npm-global/lib/node_modules/pm2/bin/pm2 startup systemd -u vrsbrazil --hp /home/vrsbrazil

Make sure you run the suggested code and you should be all set.

So there you go then, this is a good head start for you to get your Node.js service running on fail-safe mode.

This is it for this post. I hope you enjoy it, and if you can, do let me know what you are building with it on the comments.

There is still a lot to talk about on this Node.js series so please follow me on twitter @vrsbrazil so you can get notified on the next post.

Thank you very much!

Advertisements

Node.js Series: Connecting to Oracle DB

Hi!

[Versão em Português]

This is part 4 of my Node.js series, do checkout the previous posts and let me know what you think!

So we knew it would come to this, connection to Oracle DB. First of all, it does work, so what I am going to do here is the first part of the post is telling you how you do it, second part is my overall experience with this and what you should expect being your next moves. Let’s get to it then:

Acquiring the tools

Oracle provides you a mostly open-source module for your connection right here. And it works for Node 6, 8 and 10, so make sure you check your installation first. I used it with Node.JS version 10.7.0 and it worked fine.

Even though the installation process is a bit tricky, it is well documented at their github page. Keep in mind it demands the installation of Oracle client libraries into your running machine, so be warned that a simple npm i oracledb will not do!

So here is my example code:


var oracledb = require('oracledb');

oracledb.getConnection(
  {
    user          : "usr",
    password      : "pwd",
    connectString : "host:port/orcl"
  },
  function(err, connection) {
    if (err) {
      console.error(err.message);
      return;
    }
    connection.execute(
      `SELECT *
       FROM dual`,
      [],  
      function(err, result) {
        if (err) {
          console.error(err.message);
          doRelease(connection);
          return;
        }
        console.log(result.rows);
        doRelease(connection);
      });
  });

function doRelease(connection) {
  connection.close(
    function(err) {
      if (err)
        console.error(err.message);
    });
}


This code is basically a copy of the code the can be found on their github page, as you can see, there is a lot of room for improvement braking this code into components, so keep that in mind when building your production ready version.

The code above did not work the first time though, I got thrown an error:

ORA-24454: client host name is not set

All you have to do is run this on you Linux console:

sudo /bin/bash -c "echo '127.0.1.1 ${HOSTNAME}' >> /etc/hosts"

So yeah, this all I had to do in order to get this Oracle DB thing going.

It does work, BUT…

I think this solution is incomplete. As promised that is the second part with my personal opinion on the solution.

We are right now living in an environment where the high tendency is not even knowing the machine your code is running at, so offering a solution that needs local machine config in order to connect is questionable in the very least. I thought we had this figured out by the time JDBC thin clients were born. Most of Node.js customers out there are planning if not already deployed their first versions on serverless cloud providers, so it is my belief it should be reviewed.

My personal recommendation here is you should by now really start planning the usage of intermediary NoSQL databases databases like MongoDB instead of going straight to the SQL database. There are a LOT of advantages on the performance and even security realms to this strategy which we may even talk about in future post.

There are still lots to talk about on Node.js and new things are coming everyday, please follow me on twitter @vrsbrazil to follow this series and more.

Thank you!

Série Node.js: Conectando ao Oracle DB

Oi!

[English Version]

Esta é a parte 4 da minha série Node.js, veja os posts anteriores e deixe-me saber o que você pensa!

Então, sabíamos que chegaria a esse ponto, conexão com o Oracle DB. Primeiro de tudo, funciona, então o que eu vou fazer aqui é que a primeira parte do post falarei como você faz isso, a segunda parte é a minha experiência geral e o que você deve esperar de seus próximos passos. Vamos lá:

Adquirindo as ferramentas

A Oracle fornece a você um módulo de código semi aberto para sua conexão aqui . E funciona para o Node 6, 8 e 10, portanto, verifique sua instalação primeiro. Eu usei com o Node.JS versão 10.7.0 e funcionou bem.

O processo de instalação é um pouco complicado, mas está bem documentado na sua página github. Tenha em mente que a ferramenta exige a instalação de bibliotecas do cliente Oracle em seu computador que executará o código, portanto, esteja avisado que um simples npm i oracledb não funcionará!

Então aqui está o meu código de exemplo:


var oracledb = require('oracledb');

oracledb.getConnection(
  {
    user          : "usr",
    password      : "pwd",
    connectString : "host:port/orcl"
  },
  function(err, connection) {
    if (err) {
      console.error(err.message);
      return;
    }
    connection.execute(
      `SELECT *
       FROM dual`,
      [],  
      function(err, result) {
        if (err) {
          console.error(err.message);
          doRelease(connection);
          return;
        }
        console.log(result.rows);
        doRelease(connection);
      });
  });

function doRelease(connection) {
  connection.close(
    function(err) {
      if (err)
        console.error(err.message);
    });
}


Este código é basicamente uma cópia do código que pode ser encontrado em sua página github, como você pode ver, há muito espaço para melhorias na transformação deste código em componentes, então tenha isso em mente ao construir sua versão pronta para produção.

O código acima não funcionou na primeira vez, e eu tomei um erro:

ORA-24454: client host name is not set

Tudo o que você precisa fazer é executar isso no seu console Linux:

sudo /bin/bash -c "echo '127.0.1.1 ${HOSTNAME}' >> /etc/hosts"

Então, sim, isso foi tudo que eu tive que fazer para conectar ao Oracle DB.

Funciona, MAS…

Eu acho que esta solução está incompleta. Como prometido, essa é a segunda parte com minha opinião pessoal sobre ela.

Estamos agora vivendo em um ambiente em que a alta tendência é nem mesmo conhecer a máquina em que seu código está sendo executado, portanto, oferecer uma solução que precise de configuração de máquina local para conectar é, no mínimo, questionável. Eu pensei que nós tínhamos resolvido isso quando os thin clients JDBC nasceram. A maioria dos clientes Node.js está planejando, se já não implantou suas primeiras versões em provedores de nuvem serverless, eu acredito que esta estratégia deva ser revista.

Minha recomendação pessoal aqui é que você, caso ainda não tenha feito, deva começar a planejar o uso de bancos de dados intermediários NoSQL como MongoDB em vez de ir direto para o banco de dados SQL. Há um monte de vantagens no desempenho e até mesmo nos domínios de segurança para esta estratégia que podemos até mesmo falar em um futuro post.

Ainda há muito o que falar sobre o Node.js e coisas novas estão chegando todos os dias, por favor, siga-me no twitter @vrsbrazil para acompanhar esta série e mais.

Obrigado!