Node.js is a JavaScript runtime built into Chrome's JS V8 engine. The Node.js Starter Platform uses an event-driven, non-blocking I / O model, which makes it easy and efficient. The Node.js package ecosystem is the largest open source library ecosystem in the world. The project is supported by the Node.js. Foundation. Contributions, policies, and issues are controlled through an open management model.
Node.js for Beginners: Definition
Node.js is an open source development platform for running server-side JavaScript code. Node is useful for developing applications that require a constant connection from the browser to the server. Often used for real-time applications such as chat, news feeds, and push notifications.
Node.js is designed to work on a dedicated HTTP server and to use one thread with one process for one unit of time. Getting started in Node.js is event-based and runs asynchronously. The code built on this platform does not correspond to the traditional model of receiving, processing, sending, waiting and receiving. Instead, Node processes incoming requests in the constant events stack, sends small requests one by one, and does not wait for responses.
Node.JS books for beginners contain a lot of data on the transition from the basic models, which run larger, more complex processes and simultaneously run multiple threads. Each of them awaits its respective response before moving on.
The beginning of Node.js - JavaScript
Node is based on JavaScript, and therefore understanding the operation of this platform is impossible without an excursion into JS. Tutorials for Beginners Node.js contains a lot of background information about the programming language on which this platform was based. JavaScript is an interpreted programming language or script from Netscape. It is similar to the capabilities of Microsoft Visual Basic, Sun Tcl, Perl from UNIX and REXX from IBM. JavaScript scripting languages โโare easier and faster to code than more structured and compiled ones like C and C ++. Scripting languages โโusually take longer than compiled ones, but they are very useful for short programs.
JavaScript is used in website design to perform tasks such as automatically changing the formatted date on a web page. This is the reason why the linked page will be displayed in a popup window.
When changing text or graphics, JavaScript uses the same ideas as in Java (compiled object-oriented programming derived from C ++).
JS Features
JavaScript is commonly used in web development. It was originally developed by Netscape as a tool for adding dynamic and interactive elements to websites. Although JavaScript is Java-dependent, the syntax is more like C and is based on ECMAScript, a scripting language developed by Sun Microsystems.
JavaScript is a client-side scripting language. This means that the source code is processed by the clientโs web browser, not the web server. Functions can be launched after loading a web page without connecting to the server. For example, a JavaScript function may check the web form before submitting to ensure that all required fields are filled out. The code may give an error message before any information is actually transmitted to the server.
Like server-side scripting languages such as PHP and ASP, JavaScript code can be inserted anywhere on an HTML page on the web. However, HTML only displays the output of the server code, and the JavaScript code remains fully visible in the source of the web page. It can also be found in a separate .JS file, which can also be viewed in a browser.
Code Samples
The following is an example of a basic JavaScript function that adds two numbers. The function is called with parameters 7 and 11. If the code below was included in the HTML of the web page, it displayed the text โ18โ in the warning field.
<script>
function sum (a, b)
{
return a + b;
}
var total = sum (7.11);
alert (total);
</script>
JavaScript functions can be called in <script> tags, or when certain events occur. Examples include onClick, onMouseDown, onMouseUp, onKeyDown, onKeyUp, onFocus, onBlur, onSubmit and many others. Although standard JavaScript is still used to perform basic client-side functions, many web developers prefer to use JavaScript libraries, such as jQuery, to add more advanced dynamic elements to websites.
Benefits and important nuances
One of the main advantages of Node.js, according to its creator, Ryan Dahl, is that it does not block input / output (I / O). Some developers are very critical of Node.js and note that if a single process requires a significant number of processor cycles, the application is blocked. This may cause a malfunction. Proponents of the Node.js model claim that processor processing time is less worrying due to the large number of small processes on which the host code is based.
The popularity of JavaScript applications has been growing rapidly over the past few years, and Node.js is definitely contributing to this growth. If we look at the statistics, we will see that there are more Node packages in the world than similar Ruby data. Second factor: Node packages grow faster than Ruby, Python, and Java.
What makes it more popular than Rails and other alternatives to Node.JS? Where to start learning? Node itself is an event-based asynchronous platform built on top of the Chrome JavaScript engine and designed to create scalable network applications. In other words, Node.js is JavaScript plus C / C ++ in conjunction with the file system, the launch of HTTP or TCP servers.
Node is single-threaded and uses a concurrency model based on an event loop. It does not block processes and does not make the program wait, but registers a callback and allows the application to continue working. This means that the platform can handle concurrent operations without multiple threads and is efficiently scalable.
There are big differences between consecutive languages โโand Node.js:
Node allows you to perform other tasks, waiting for notification when a response is available;
the application does not buffer data into memory, but instead outputs it fragmented.
Although there are other event loop systems (such as the EventMachine library in Ruby or Twisted in Python), there is a significant difference between them and Node.
In Node.JS, all libraries were designed from the ground up to be non-blocking, which cannot be said of others.
Use cases
Node is ideal for I / O-bound applications, but not so good for applications with a heavy processor. Great examples are real-time (DIRT) applications, single-page applications, JSON APIs, and streaming applications.
Official Node Package Manager (NPM)
Node owes much of its success to the package manager that comes with it. Advantages of this tool:
It installs application dependencies locally, not globally;
at the same time it processes several versions of the same module;
you can specify tarballs or git repositories as dependencies;
It's very easy to publish your own module in the NPM registry.
Install Node.js
For beginners, there are official installers for Node on Windows and OS X, and the option of installing through the package manager is also provided. To test user code with different versions of nodes, NVM (Node version manager) is used.
With this tool, you can use several versions of the node installed in the system and easily switch between them. In the next few lines, we will see how to install NVM on an Ubuntu system.
First, we need to make sure that our system has a C ++ compiler:
$ sudo apt-get update
$ sudo apt-get install build-essential libssl-dev
After that we can copy and paste the single-line installer for NVM into the terminal:
$ curl https://raw.githubusercontent.com/creationix/nvm/v0.13.1/install.sh | hit
NVM must be installed correctly, so we log out and log in to make sure everything is correct. Enter the command:
$ nvm
If the input does not cause an error, this means that everything is in order. Now we can move on to the actual installation of Node and NPM.
The result on the command line should look like this:
$ nvm install v0.10.31
####################################################### ################# 100.0%
Now both nodes and npm should be accessible in the terminal:
$ node -v & amp; & amp; & amp; npm -v
v0.10.31
1.4.23
Now you need to configure the default launch of Node.JS using the command in the terminal:
$ nvm alias default 0.10.31
We can install other versions of Node in the same way as before, and switch between them using the nvm use command:
$ nvm install v0.8.10
If you do not know which versions are installed on your system, simply enter nvm-list. This tool will show you a complete list, as well as current and default versions, for example:
list $ nvm
v0.6.3 v0.6.12 v0.6.14 v0.6.19 v0.7.7 v0.7.8 v0.7.9 v0.8.6 v0.8.11 v0.10.3 v0.10.12 v0.10.15 v0.10.21 v0.10.24 v0.11.9 current: v0.10.24 default -> v0.10.24
Modules
The Node.JS tutorial for Java or Python beginners requires the use of the import function to load other libraries, while the use of PHP and Ruby does not require this. Node implements the CommonJS interface for modules. You can also load other options using the require keyword.
For example, we may need some proprietary modules:
var http = require ('http');
var dns = require ('dns');
We can also call relative files:
var myFile = require ('./ myFile'); // download myFile.js
To install NPM modules, search for them on a website or on Github. The syntax for installing the module locally is quite simple:
# where express === module name
$ npm install express
Callbacks
In asynchronous programming, we do not return values โโwhen functions are executed, but instead use the Continue Continuation (CPS) style. Using this style, an asynchronous function calls a callback (a function usually passed as the last argument) to continue the program after it finishes.
The following is an example of finding IPv4 addresses for a domain:
var dns = require ('dns');
dns.resolve4 ('www.google.com', function (err, addresses) {
if (err) throw err;
console.log ('addresses:' + JSON.stringify (addresses));
});
We passed the callback (built-in anonymous function) as the second argument to the asynchronous dns.resolve4. Once the async function is ready, it will call a callback, continuing the program.
Events
The Beginner's Guide in Node.JS introduces a standard callback template that works well for use cases where we want to be notified when the asynchronization function completes. However, there are situations that require notification of various events that do not occur simultaneously.
Let's look at this with an example of code with an IRC client:
var irc = require ('irc');
var client = new irc.Client ('irc.freenode.net', 'myIrcBot', {
channels: ['# sample-channel']
});
client.on ('error', function (message) {
console.error ('error:', message);
});
client.on ('connect', function () {
console.log ("connected to the irc server");
});
client.on ('message', function (from, to, message) {
console.log (from + '=>' + to + ':' + message);
});
client.on ('pm', function (from, message) {
console.log (from + '=> ME: + message);
}).
In the above example, we are dealing with three types of events:
a connection event is thrown when the client successfully connected to the IRC server;
an error event is triggered if an error occurs;
Messages and pm events are selected for incoming messages.
The above events make this situation ideal for using the EventEmitter pattern.
The EventEmitter template allows developers to release an event that consumers can subscribe to if they are interested. This template may be familiar with the browser, where it is used to attach event handlers.
Node has an EventEmitter class in the kernel that we can use to create our own EventEmitter objects. Let's try to create a MemoryWatcher class that inherits an EventEmitter and generates two types of events:
data at regular intervals, which represents the use of memory in bytes;
an error event if the memory exceeds a certain limit.
So, Node is not a web server, but one way to create code on a computer. It is a javascript runtime.