Tutorials / Preparing node.js environment

5f3f2d7c-194d-7aee-b16e-72e3de3a5f38

Running JavaScript code by node.js

Before we start working with RabbitMQ server with node.js, it is good to know, how to run JavaScript code from command line.

It's done because node.js is not only web server, but also .js files interpreter, the same as e.g. Bash is interpreter for .sh scripts in Linux.

Let's write the simplest program in JavaScript, which we could run by node.js:

#!/usr/bin/env node
console.log("Welcome in Node.js World!");

Such scripts can be executed in console, which means that one need to enter following command to run them:

$ ./welcome.js
Welcome in Node.js World

To be able to do above command the file need to have execute permission, which is marked with x letter, when one is listing directory as follow:

$ ls -al
-rwxr-xr-x 1 tomasz tomasz 396 sep 21 19:43 welcome.js

Connecting to RabbitMQ with amqplib

Before we start to write program in JavaScript, we need to install the amqplib library in the project directory, which provides the communication interface to the RabbitMQ server. This library is not delivered along with the message broker, but it is recommended by its creators.

Installing amqplib library

To install this libvrary we need to create a file, which describe project dependencies (package.json), which is managed by node.js package manager — npm:

{
  "name": "rattique-tutorials-en-node-js",
  "version": "0.7.0",
  "description": "RabbitMQ tutorial for node.js environment",
  "email": "tkuter@loculus.pl",
  "dependencies": {
    "amqplib": "^0.4"
  },
  "keywords": [
    "AMQP",
    "AMQP 0-9-1",
    "RabbitMQ",
    "RattiQue",
    "node.js",
    "amqplib"
  ],
  "author": "Tomasz Kuter <tkuter@loculus.pl>",
  "license": "MIT"
}

When such file is made, one needs to execute following command:

$ npm install

and all project dependencies (packages) will be resolved, downloaded and installed in the subdirectory: node_modules.

In next step we will create first two programs:

  • message sender, which sends data to the queue
  • and message receiver, which gets data from it.

This will be part of the next tutorial in this series.

Source code repository

Related source code is stored in the repository on the following website: https://github.com/RattiQue/tutorials-en-node.js

Tomasz Kuter

Web Developer with over 8 years of commercial experience in making websites, web applications and administration panels in PHP, JavaScript, HTML and CSS.
Currently focused on microservice architecture, which allows to build scalable web applications.