📜 ⬆️ ⬇️

Using Node.js technology as a platform for optimizing server capacity

image

Web programming is rapidly evolving and there is a need to choose between mature languages ​​such as PERL, C ++ and Java and modern web-oriented or prototype-oriented languages ​​like Ruby or Go. One such language is javascript. For many years there was an opinion that JavaScript is a client-oriented programming language and it has no future, but after Google released a stable version of the V8 JavaScript engine, Node.js appeared and began to be used as a completely new idea, server-side JavaScript.

Node.js continues to evolve dynamically and ambitiously. For example, over the past few years, developers have added about 200,000 modules for Node.js, which is several times faster than the development of already established server languages, such as Perl, which has fewer modules in the repository. It is also necessary to emphasize that the Node.js technology is gaining momentum and is used by companies such as Yahoo, Microsoft, PayPal and LinkedIn, not to mention Google.

Node.js is designed for tasks that have a web infrastructure and mobile applications, in the back-end of which you need to make changes in real-time mode using the architecture built on the basis of microservices. Node.js can significantly reduce the time to develop an application without changing the application logic.

Node.js is also suitable for applications built on the basis of microservice architecture, due to the low consumption of processor resources, its efficient use of RAM and computing power. To a greater extent, this is noticeable in tasks related to operations that consume a lot of I / O memory, rather than processor use, since the approach to implementing the Node.js execution model allows you to simulate the parallelism of a task based on a consistent execution flow model that does not require complex parallel programming techniques.
')


To build your own solutions, you can use ready-made modules that simply adapt to a specific project. For example, one of the most common Web application frameworks is “Express”, the database can be used as a relational (MySql) or non-relational (MongoDB), you can also use various modules for variation and formatting of data.

Installing Node.js and NPM under Linux (Ubuntu 16.04):

sudo apt-get install nodejs sudo apt-get install npm 

Installing the WS, FS, Mysql, and MongoDB libraries from NPM:

 npm install ws // -  npm install fs //       npm install mysql //  mysql  npm install –g mongodb // mongodb   

An example of establishing a database connection:

 var url = 'mongodb://127.0.0.1:27017'; var db = '/your_collection'; // init DB var MongoClient = require('mongodb').MongoClient; // connect with mongo MongoClient.connect(url + db, function (err, mongoclient) { if (err) {throw err} var db_object = mongoclient.collection('collection'); db_object.find({_id:some_id}); }); 

To run the nodejs script, you need to call the command from the same directory where you installed the npm packages, i.e. at the same level with the folder "node_modules":

 nodejs __/_.js 

Due to the fact that Node.js has an excellent tool, NPM is a package manager, with its help you can manage modules and dependencies. It is easy to use and scale within the server environment. So for example using Node.js for several projects we can install packages / modules both globally and locally.

There are also a number of additional tools for comfortable work with Node.js. For example, to maintain processes, use utilities: forever or supervisor. The first is installed from the NPM package manager and serves only to support the Node.js processes, while the second is able to work with other utilities such as RabbitMQ, Bash Scripts and is thus more universal. There is also a supervisor module which is installed as a package for Node.js and plays the role of an observer for changes in the script and automatic restarting without leakage of RAM memory and without clearing inter-module dependencies.

Supervisor installation:

 sudo apt-get install supervisor 

The supervisor configuration file is located in the directory: / etc / supervisor /

To enable access via the web interface, add to /etc/supervisor/supervisord.conf file:

 [inet_http_server] port=*:9001 username= password= 

For the project, you need to create a configuration file for launching the node.js script in the directory:
/etc/supervisor/conf.d/file.conf:

 [program:_] directory=/// command=nodejs __/_.js autostart=true autorestart=true stderr_logfile=/var/log/supervisor/_.err.log stdout_logfile=/var/log/supervisor/_.out.log 

Node.js also has a number of modules for logging, the most popular (log4j, winston, bunyan, intel). They allow logging both application script and system messages directly (ERROR, WARN, INFO, DEBUG, TRACE). To return errors to functions, a synchronous approach (throw) or an asynchronous approach (callback function or event) can be implemented, but you cannot implement both approaches in one function. When using a function, in order to handle the errors arising in it, you will need to use either callback functions or a try / catch construct.

Node.js also knows how to work with files. For this, it uses the FS module from the NPM package builder. Its huge advantage over other modules is that almost all file processing functions have two types of synchronous reading and asynchronous file reading. The same module can work both with data in different encodings, and with integers, fractional numbers, with numbers in the Double format, etc.

Example of an asynchronous file reading (without waiting):

 var fs = require('fs'); fs.readFile('', 'utf8', function(err, data) { console.log(data); }); console.log('after readFile'); 

Example of synchronous file reading (with wait):

 var fs = require('fs'); var data = fs.readFileSync('', 'utf8'); console.log(data); 

We give the simplest test for the output of “Hello World” and see with the dstat utility what indicators we will get:
nodejs:
 var sys = require('sys'), http = require('http'); http.createServer(function(req, res){ res.writeHead(200, {'Content-Type': 'text/html'}); res.write('<p>Hello World</p>'); res.end(); }).listen(8080); 

php:
 <?php echo '<p>Hello World</p>'; 

Result:
image

image

image

Despite the fact that Node.js does not seek to take the place of other programming languages, it has already shown itself as a promising technology. Speaking of web-sockets-based server solutions for web and mobile-application, Node.js confidently protects its positions.

Source: https://habr.com/ru/post/319368/


All Articles