Node js javascript runtime что это
Перейти к содержимому

Node js javascript runtime что это

  • автор:

What exactly is Node.js?

Priyesh Patel

Node.js is a JavaScript runtime environment. Sounds great, but what does that mean? How does that work?

The Node run-time environment includes everything you need to execute a program written in JavaScript.

Node.js came into existence when the original developers of JavaScript extended it from something you could only run in the browser to something you could run on your machine as a standalone application.

Now you can do much more with JavaScript than just making websites interactive.

JavaScript now has the capability to do things that other scripting languages like Python can do.

Both your browser JavaScript and Node.js run on the V8 JavaScript runtime engine. This engine takes your JavaScript code and converts it into a faster machine code. Machine code is low-level code which the computer can run without needing to first interpret it.

Why Node.js?

Here’s a formal definition as given on the official Node.js website:

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.

Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.

Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

We already discussed the first line of this definition: “Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine.” Now let’s understand the other two lines so we can find out why Node.js is so popular.

I/O refers to input/output. It can be anything ranging from reading/writing local files to making an HTTP request to an API.

I/O takes time and hence blocks other functions.

Consider a scenario where we request a backend database for the details of user1 and user2 and then print them on the screen/console. The response to this request takes time, but both of the user data requests can be carried out independently and at the same time.

Blocking I/O

In the blocking method, user2's data request is not initiated until user1's data is printed to the screen.

If this was a web server, we would have to start a new thread for every new user. But JavaScript is single-threaded (not really, but it has a single-threaded event loop, which we’ll discuss a bit later). So this would make JavaScript not very well suited for multi-threaded tasks.

That’s where the non-blocking part comes in.

Non-blocking I/O

On the other hand, using a non-blocking request, you can initiate a data request for user2 without waiting for the response to the request for user1. You can initiate both requests in parallel.

This non-blocking I/O eliminates the need for multi-threading since the server can handle multiple requests at the same time.

The JavaScript event loop

If you have 26 minutes, watch this excellent video explanation of the Node Event Loop:

Otherwise, here’s a quick step-by-step explanation of how the JavaScript Event Loop works.

  1. Push main() onto the call stack.
  2. Push console.log() onto the call stack. This then runs right away and gets popped.
  3. Push setTimeout(2000) onto the stack. setTimeout(2000) is a Node API. When we call it, we register the event-callback pair. The event will wait 2000 milliseconds, then callback is the function.
  4. After registering it in the APIs, setTimeout(2000) gets popped from the call stack.
  5. Now the second setTimeout(0) gets registered in the same way. We now have two Node APIs waiting to execute.
  6. After waiting for 0 seconds, setTimeout(0) gets moved to the callback queue, and the same thing happens with setTimeout(2000) .
  7. In the callback queue, the functions wait for the call stack to be empty, because only one statement can execute a time. This is taken care of by the event loop.
  8. The last console.log() runs, and the main() gets popped from the call stack.
  9. The event loop sees that the call stack is empty and the callback queue is not empty. So it moves the callbacks (in a first-in-first-out order) to the call stack for execution.

These are libraries built by the awesome community which will solve most of your generic problems. npm (Node package manager) has packages you can use in your apps to make your development faster and efficient.

Require

Require does three things:

  • It loads modules that come bundled with Node.js like file system and HTTP from the Node.js API .
  • It loads third-party libraries like Express and Mongoose that you install from npm.
  • It lets you require your own files and modularize the project.

Require is a function, and it accepts a parameter “path” and returns module.exports .

Node Modules

A Node module is a reusable block of code whose existence does not accidentally impact other code.

You can write your own modules and use it in various application. Node.js has a set of built-in modules which you can use without any further installation.

V8 turbo-charges JavaScript by leveraging C++

V8 is an open source runtime engine written in C++.

JavaScript -> V8(C++) -> Machine Code

V8 implements a script called ECMAScript as specified in ECMA-262. ECMAScript was created by Ecma International to standardize JavaScript.

V8 can run standalone or can be embedded into any C++ application. It has hooks that allow you to write your own C++ code that you can make available to JavaScript.

This essentially lets you add features to JavaScript by embedding V8 into your C++ code so that your C++ code understands more than what the ECMAScript standard otherwise specifies.

Edit: As brought to my attention by Greg Bulmash, there are many different JavaScript runtime engines apart from V8 by Chrome like SpiderMonkey by Mozilla, Chakra by Microsoft, etc. Details of the same can be found on this page.

Events

Something that has happened in our app that we can respond to. There are two types of events in Node.

Name already in use

Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Node.js is an open-source, cross-platform JavaScript runtime environment.

For information on using Node.js, see the Node.js website.

The Node.js project uses an open governance model. The OpenJS Foundation provides support for the project.

Contributors are expected to act in a collaborative manner to move the project forward. We encourage the constructive exchange of contrary opinions and compromise. The TSC reserves the right to limit or block contributors who repeatedly act in ways that discourage, exhaust, or otherwise negatively affect other participants.

This project has a Code of Conduct.

Table of contents

  • Current: Under active development. Code for the Current release is in the branch for its major version number (for example, v19.x). Node.js releases a new major version every 6 months, allowing for breaking changes. This happens in April and October every year. Releases appearing each October have a support life of 8 months. Releases appearing each April convert to LTS (see below) each October.
  • LTS: Releases that receive Long Term Support, with a focus on stability and security. Every even-numbered major version will become an LTS release. LTS releases receive 12 months of Active LTS support and a further 18 months of Maintenance. LTS release lines have alphabetically-ordered code names, beginning with v4 Argon. There are no breaking changes or feature additions, except in some special circumstances.
  • Nightly: Code from the Current branch built every 24-hours when there are changes. Use with caution.

Current and LTS releases follow semantic versioning. A member of the Release Team signs each Current and LTS release. For more information, see the Release README.

Binaries, installers, and source tarballs are available at https://nodejs.org/en/download/.

Current and LTS releases

The latest directory is an alias for the latest Current release. The latest-codename directory is an alias for the latest release from an LTS line. For example, the latest-hydrogen directory contains the latest Hydrogen (Node.js 18) release.

Each directory name and filename contains a date (in UTC) and the commit SHA at the HEAD of the release.

Documentation for the latest Current release is at https://nodejs.org/api/. Version-specific documentation is available in each release directory in the docs subdirectory. Version-specific documentation is also at https://nodejs.org/download/docs/.

Download directories contain a SHASUMS256.txt file with SHA checksums for the files.

To download SHASUMS256.txt using curl :

To check that a downloaded file matches the checksum, run it through sha256sum with a command such as:

For Current and LTS, the GPG detached signature of SHASUMS256.txt is in SHASUMS256.txt.sig . You can use it with gpg to verify the integrity of SHASUMS256.txt . You will first need to import the GPG keys of individuals authorized to create releases. To import the keys:

See Release keys for a script to import active release keys.

Next, download the SHASUMS256.txt.sig for the release:

Then use gpg —verify SHASUMS256.txt.sig SHASUMS256.txt to verify the file’s signature.

See BUILDING.md for instructions on how to build Node.js from source and a list of supported platforms.

For information on reporting security vulnerabilities in Node.js, see SECURITY.md.

Contributing to Node.js

Current project team members

For information about the governance of the Node.js project, see GOVERNANCE.md.

TSC (Technical Steering Committee)

TSC voting members

    Antoine du Hamel <duhamelantoine1995@gmail.com> (he/him) — Anatoli Papirovski <apapirovski@mac.com> (he/him) — Ruben Bridgewater <ruben@bridgewater.de> (he/him) — Colin Ihrig <cjihrig@gmail.com> (he/him) — Danielle Adams <adamzdanielle@gmail.com> (she/her) — Geoffrey Booth <webadmin@geoffreybooth.com> (he/him) — Gireesh Punathil <gpunathi@in.ibm.com> (he/him) — James M Snell <jasnell@gmail.com> (he/him) — Joyee Cheung <joyeec9h3@gmail.com> (she/her) — Chengzhong Wu <legendecas@gmail.com> (he/him) — Matteo Collina <matteo.collina@gmail.com> (he/him) — Michael Dawson <midawson@redhat.com> (he/him) — Moshe Atlow <moshe@atlow.co.il> (he/him) — Rafael Gonzaga <rafael.nunu@hotmail.com> (he/him) — Darshan Sen <raisinten@gmail.com> (he/him) — Richard Lau <rlau@redhat.com> — Robert Nagy <ronagy@icloud.com> — Ruy Adorno <ruyadorno@google.com> (he/him) — Michaël Zasso <targos@protonmail.com> (he/him) — Tobias Nießen <tniessen@tnie.de> (he/him) — Rich Trott <rtrott@gmail.com> (he/him)

TSC regular members

    Beth Griggs <bethanyngriggs@gmail.com> (she/her) — Ben Noordhuis <info@bnoordhuis.nl> — Сковорода Никита Андреевич <chalkerx@gmail.com> (he/him) — Shelley Vohr <shelley.vohr@gmail.com> (she/her) — Daniel Bevenius <daniel.bevenius@gmail.com> (he/him) — Franziska Hinkelmann <franziska.hinkelmann@gmail.com> (she/her) — Gabriel Schulhof <gabrielschulhof@gmail.com> — Brian White <mscdex@mscdex.net> — Myles Borins <myles.borins@gmail.com> (he/him) — Rod Vagg <r@va.gg> — Tiancheng «Timothy» Gu <timothygu99@gmail.com> (he/him)

TSC emeriti members

    Anna Henningsen <anna@addaleax.net> (she/her) — Chris Dickinson <christopher.s.dickinson@gmail.com> — Evan Lucas <evanlucas@me.com> (he/him) — Jeremiah Senkpiel <fishrock123@rocketmail.com> (he/they) — Gibson Fahnestock <gibfahn@gmail.com> (he/him) — Fedor Indutny <fedor@indutny.com> — Isaac Z. Schlueter <i@izs.me> — Josh Gavant <josh.gavant@outlook.com> — Mary Marchini <oss@mmarchini.me> (she/her) — Bryan Hughes <bryan@nebri.us> — Ali Ijaz Sheikh <ofrobots@google.com> (he/him) — Alexis Campailla <orangemocha@nodejs.org> — Bert Belder <bertbelder@gmail.com> — Sam Roberts <vieuxtech@gmail.com> — Shigeki Ohtsu <ohtsu@ohtsu.org> (he/him) — Sakthipriyan Vairamani <thechargingvolcano@gmail.com> (he/him) — Trevor Norris <trev.norris@gmail.com>
    Anna Henningsen <anna@addaleax.net> (she/her) — Antoine du Hamel <duhamelantoine1995@gmail.com> (he/him) — Yagiz Nizipli <yagiz@nizipli.com> (he/him) — Anto Aravinth <anto.aravinth.cse@gmail.com> (he/him) — Anatoli Papirovski <apapirovski@mac.com> (he/him) — Ash Cripps <email@ashleycripps.co.uk> — Qingyu Deng <i@ayase-lab.com> — Bryan English <bryan@bryanenglish.com> (he/him) — Benjamin Gruenbaum <benjamingr@gmail.com> — Beth Griggs <bethanyngriggs@gmail.com> (she/her) — Bradley Farias <bradley.meck@gmail.com> — Tierney Cyren <hello@bnb.im> (they/he) — Ben Noordhuis <info@bnoordhuis.nl> — Ruben Bridgewater <ruben@bridgewater.de> (he/him) — Christian Clauss <cclauss@me.com> (he/him) — Сковорода Никита Андреевич <chalkerx@gmail.com> (he/him) — Colin Ihrig <cjihrig@gmail.com> (he/him) — Shelley Vohr <shelley.vohr@gmail.com> (she/her) — Kohei Ueno <kohei.ueno119@gmail.com> (he/him) — Daeyeon Jeong <daeyeon.dev@gmail.com> (he/him) — Daniel Bevenius <daniel.bevenius@gmail.com> (he/him) — Danielle Adams <adamzdanielle@gmail.com> (she/her) — Debadree Chatterjee <debadree333@gmail.com> (he/him) — Deokjin Kim <deokjin81.kim@gmail.com> (he/him) — David Carlier <devnexen@gmail.com> — Gus Caplan <me@gus.host> (they/them) — Adrian Estrada <edsadr@gmail.com> (he/him) — Erick Wendel <erick.workspace@gmail.com> (he/him) — Franziska Hinkelmann <franziska.hinkelmann@gmail.com> (she/her) — Feng Yu <F3n67u@outlook.com> (he/him) — Gerhard Stöbich <deb2001-github@yahoo.de> (he/they) — Gabriel Schulhof <gabrielschulhof@gmail.com> — Jiawen Geng <technicalcute@gmail.com> — Geoffrey Booth <webadmin@geoffreybooth.com> (he/him) — Gireesh Punathil <gpunathi@in.ibm.com> (he/him) — Guy Bedford <guybedford@gmail.com> (he/him) — Harshitha K P <harshitha014@gmail.com> (she/her) — Zeyu «Alex» Yang <himself65@outlook.com> (he/him) — Ian Sutherland <ian@iansutherland.ca> — Jackson Tian <shyvo1987@gmail.com> — Jacob Smith <jacob@frende.me> (he/him) — James M Snell <jasnell@gmail.com> (he/him) — Jan Krems <jan.krems@gmail.com> (he/him) — Joe Sepi <sepi@joesepi.com> (he/him) — Joyee Cheung <joyeec9h3@gmail.com> (she/her) — Juan José Arboleda <soyjuanarbol@gmail.com> (he/him) — Minwoo Jung <nodecorelab@gmail.com> (he/him) — Matthew Aitken <maitken033380023@gmail.com> (he/him) — Yoshiki Kurihara <yosyos0306@gmail.com> (he/him) — Chengzhong Wu <legendecas@gmail.com> (he/him) — Shingo Inoue <leko.noor@gmail.com> (he/him) — Nitzan Uziely <linkgoron@gmail.com> — LiviaMedeiros <livia@cirno.name> — Luigi Pinca <luigipinca@gmail.com> (he/him) — Luke Karrys <luke@lukekarrys.com> (he/him) — Zijian Liu <lxxyxzj@gmail.com> (he/him) — Marco Ippolito <marcoippolito54@gmail.com> (he/him) — Akhil Marsonya <akhil.marsonya27@gmail.com> (he/him) — Matteo Collina <matteo.collina@gmail.com> (he/him) — Xuguang Mei <meixuguang@gmail.com> (he/him) — Mestery <mestery@protonmail.com> (he/him) — Michael Dawson <midawson@redhat.com> (he/him) — Milad Fa <mfarazma@redhat.com> (he/him) — Alba Mendez <me@alba.sh> (she/her) — Moshe Atlow <moshe@atlow.co.il> (he/him) — Brian White <mscdex@mscdex.net> — Myles Borins <myles.borins@gmail.com> (he/him) — Claudio Wunder <cwunder@gnome.org> (he/they) — Ouyang Yadong <oyydoibh@gmail.com> (he/him) — Filip Skokan <panva.ip@gmail.com> (he/him) — Stephen Belanger <admin@stephenbelanger.com> (he/him) — Rafael Gonzaga <rafael.nunu@hotmail.com> (he/him) — Darshan Sen <raisinten@gmail.com> (he/him) — Richard Lau <rlau@redhat.com> — Ricky Zhou <0x19951125@gmail.com> (he/him) — Robert Nagy <ronagy@icloud.com> — Ruy Adorno <ruyadorno@google.com> (he/him) — Rod Vagg <rod@vagg.org> — Ujjwal Sharma <ryzokuken@disroot.org> (he/him) — Santiago Gimeno <santiago.gimeno@gmail.com> — Masashi Hirano <shisama07@gmail.com> (he/him) — Paolo Insogna <paolo@cowtech.it> (he/him) — Steven R Loomis <srl295@gmail.com> — Stewart X Addison <sxa@redhat.com> (he/him) — Michaël Zasso <targos@protonmail.com> (he/him) — theanarkh <theratliter@gmail.com> (he/him) — Tiancheng «Timothy» Gu <timothygu99@gmail.com> (he/him) — Tobias Nießen <tniessen@tnie.de> (he/him) — Trivikram Kamat <trivikr.dev@gmail.com> — Rich Trott <rtrott@gmail.com> (he/him) — Vladimir de Turckheim <vlad2t@hotmail.com> (he/him) — Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com> (he/him) — Daijiro Wachi <daijiro.wachi@gmail.com> (he/him) — Khaidi Chu <i@2333.moe> (he/him) — Yash Ladha <yash@yashladha.in> (he/him) — Yongsheng Zhang <zyszys98@gmail.com> (he/him)
    Aleksei Koziatinskii <ak239spb@gmail.com> — Andras <andras@kinvey.com> — Anna M. Kedzierska <anna.m.kedzierska@gmail.com> — Andreas Madsen <amwebdk@gmail.com> (he/him) — Alexey Orlenko <eaglexrlnk@gmail.com> (he/him) — Ben Coe <bencoe@gmail.com> (he/him) — Benedikt Meurer <benedikt.meurer@gmail.com> — Christopher Hiller <boneskull@boneskull.com> (he/him) — Brendan Ashworth <brendan.ashworth@me.com> — Bartosz Sosnowski <bartosz@janeasystems.com> — Calvin Metcalf <calvin.metcalf@gmail.com> — Chris Dickinson <christopher.s.dickinson@gmail.com> — Claudio Rodriguez <cjrodr@yahoo.com> — David Cai <davidcai1993@yahoo.com> (he/him) — Jamie Davis <davisjam@vt.edu> (he/him) — Hitesh Kanwathirtha <digitalinfinity@gmail.com> (he/him) — Xu Meng <dmabupt@gmail.com> (he/him) dnlup <dnlup.dev@gmail.com> — Robert Jefe Lindstaedt <robert.lindstaedt@gmail.com> — Alexander Makarenko <estliberitas@gmail.com> — Eugene Ostroukhov <eostroukhov@google.com> — Evan Lucas <evanlucas@me.com> (he/him) — Daniel Wang <wangyang0123@gmail.com> — Jeremiah Senkpiel <fishrock123@rocketmail.com> (he/they) — George Adams <gadams@microsoft.com> (he/him) — Wyatt Preul <wpreul@gmail.com> — Gibson Fahnestock <gibfahn@gmail.com> (he/him) — Glen Keane <glenkeane.94@gmail.com> (he/him) — Yang Guo <yangguo@chromium.org> (he/him) — Yuta Hiroto <hello@hiroppy.me> (he/him) — Rebecca Turner <me@re-becca.org> — Imran Iqbal <imran@imraniqbal.org> — Ilkka Myller <ilkka.myller@nodefield.com> — Fedor Indutny <fedor@indutny.com> — Isaac Z. Schlueter <i@izs.me> — Italo A. Casas <me@italoacasas.com> (he/him) — Jason Ginchereau <jasongin@microsoft.com> — Johan Bergström <bugs@bergstroem.nu> — John-David Dalton <john.david.dalton@gmail.com> — Yuval Brik <yuval@brik.org.il> — João Reis <reis@janeasystems.com> — Josh Gavant <josh.gavant@outlook.com> — Julian Duque <julianduquej@gmail.com> (he/him) — Kyle Farnung <kfarnung@microsoft.com> (he/him) — Kunal Pathak <kunal.pathak@microsoft.com> — Lance Ball <lball@redhat.com> (he/him) — Luca Maraschi <luca.maraschi@gmail.com> (he/him) — Denys Otrishko <shishugi@gmail.com> (he/him) — Aleksey Smolenchuk <lxe@lxe.co> — Jon Moss <me@jonathanmoss.me> (he/him) — Mathias Buus <mathiasbuus@gmail.com> (he/him) — Matthew Loring <mattloring@google.com> — Nicu Micleușanu <micnic90@gmail.com> (he/him) — Mikeal Rogers <mikeal.rogers@gmail.com> — Julien Gilli <jgilli@netflix.com> — Mary Marchini <oss@mmarchini.me> (she/her) — Christopher Monsanto <chris@monsan.to> — Chen Gang <gangc.cxy@foxmail.com> — Teddy Katz <teddy.katz@gmail.com> (he/him) — Ali Ijaz Sheikh <ofrobots@google.com> (he/him) — Oleg Elifantiev <oleg@elifantiev.ru> — Alexis Campailla <orangemocha@nodejs.org> — Forrest L Norvell <ogd@aoaioxxysz.net> (they/them/themself) — Petka Antonov <petka_antonov@hotmail.com> — Phillip Johnsen <johphi@gmail.com> — Bert Belder <bertbelder@gmail.com> — Minqi Pan <pmq2001@gmail.com> — Pooja D P <Pooja.D.P@ibm.com> (she/her) — Prince John Wesley <princejohnwesley@gmail.com> — Peter Marshall <petermarshall@chromium.org> (he/him) — Andrey Pechkurov <apechkurov@gmail.com> (he/him) — Refael Ackermann (רפאל פלחי) <refack@gmail.com> (he/him/הוא/אתה) — Pranshu Srivastava <rexagod@gmail.com> (he/him) — Alex Kocharin <alex@kocharin.ru> — Ryan Graham <r.m.graham@gmail.com> — Robert Kowalski <rok@kowalski.gd> — Roman Klauke <romaaan.git@gmail.com> — Ron Korving <ron@ronkorving.nl> — Ingvar Stepanyan <me@rreverser.com> — Sam Ruby <rubys@intertwingly.net> — Saúl Ibarra Corretgé <s@saghul.net> — Sam Roberts <vieuxtech@gmail.com> — Sebastiaan Deckers <sebdeckers83@gmail.com> — Nikolai Vavilov <vvnicholas@gmail.com> — Shigeki Ohtsu <ohtsu@ohtsu.org> (he/him) — Roman Reiss <me@silverwind.io> — Weijia Wang <starkwang@126.com> — Stefan Budeanu <stefan@budeanu.com> — Christian Tellnes <christian@tellnes.no> — Sakthipriyan Vairamani <thechargingvolcano@gmail.com> (he/him) — Thorsten Lorenz <thlorenz@gmx.de> — Trevor Norris <trev.norris@gmail.com> — Mike Tunnicliffe <m.j.tunnicliffe@gmail.com> — Vladimir Kurchatkin <vladimir.kurchatkin@gmail.com> — Vse Mozhet Byt <vsemozhetbyt@gmail.com> (he/him) — Thomas Watson <w@tson.dk> — Jeremy Whitlock <jwhitlock@apache.org> — Yihong Wang <yh.wang@ibm.com> — Yorkie Liu <yorkiefixer@gmail.com> — Yosuke Furukawa <yosuke.furukawa@gmail.com>

Collaborators follow the Collaborator Guide in maintaining the Node.js project.

    Chemi Atlow <chemi@atlow.co.il> (he/him) — Qingyu Deng <i@ayase-lab.com> — Brian Muenzenmeyer <brian.muenzenmeyer@gmail.com> (he/him) — Daeyeon Jeong <daeyeon.dev@gmail.com> (he/him) — Feng Yu <F3n67u@outlook.com> (he/him) — Himadri Ganguly <himadri.tech@gmail.com> (he/him) — Frank Qiu <iam.frankqiu@gmail.com> (he/him) — Keyhan Vakil <kvakil@sylph.kvakil.me> (they/them) — Akhil Marsonya <akhil.marsonya27@gmail.com> (he/him) — Xuguang Mei <meixuguang@gmail.com> (he/him) — Mestery <mestery@protonmail.com> (he/him) — Pooja Durgad <Pooja.D.P@ibm.com> — Darshan Sen <raisinten@gmail.com> — Mohammed Keyvanzadeh <mohammadkeyvanzade94@gmail.com> (he/him)

Triagers follow the Triage Guide when responding to new issues.

Primary GPG keys for Node.js Releasers (some Releasers sign with subkeys):

  • Beth Griggs <bethanyngriggs@gmail.com> 4ED778F539E3634C779C87C6D7062848A1AB005C
  • Bryan English <bryan@bryanenglish.com> 141F07595B7B3FFE74309A937405533BE57C7D57
  • Danielle Adams <adamzdanielle@gmail.com> 74F12602B6F1C4E913FAA37AD3A89613643B6201
  • Juan José Arboleda <soyjuanarbol@gmail.com> DD792F5973C6DE52C432CBDAC77ABFA00DDBF2B7
  • Michaël Zasso <targos@protonmail.com> 8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600
  • Myles Borins <myles.borins@gmail.com> C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8
  • RafaelGSS <rafael.nunu@hotmail.com> 890C08DB8579162FEE0DF9DB8BEAB4DFCF555EF4
  • Richard Lau <rlau@redhat.com> C82FA3AE1CBEDC6BE46B9360C43CEC45C17AB93C
  • Ruy Adorno <ruyadorno@hotmail.com> 108F52B48DB57BB0CC439B2997B01419BD92F80A

To import the full set of trusted release keys (including subkeys possibly used to sign releases):

See Verifying binaries for how to use these keys to verify a downloaded file.

  • Chris Dickinson <christopher.s.dickinson@gmail.com> 9554F04D7259F04124DE6B476D5A82AC7E37093B
  • Colin Ihrig <cjihrig@gmail.com> 94AE36675C464D64BAFA68DD7434390BDBE9B9C5
  • Danielle Adams <adamzdanielle@gmail.com> 1C050899334244A8AF75E53792EF661D867B9DFA
  • Evan Lucas <evanlucas@me.com> B9AE9905FFD7803F25714661B63B535A4C206CA9
  • Gibson Fahnestock <gibfahn@gmail.com> 77984A986EBC2AA786BC0F66B01FBB92821C587A
  • Isaac Z. Schlueter <i@izs.me> 93C7E9E91B49E432C2F75674B0A78B0A6C481CF6
  • Italo A. Casas <me@italoacasas.com> 56730D5401028683275BD23C23EFEFE93C4CFFFE
  • James M Snell <jasnell@keybase.io> 71DCFD284A79C3B38668286BC97EC7A07EDE3FC1
  • Jeremiah Senkpiel <fishrock@keybase.io> FD3A5288F042B6850C66B31F09FE44734EB7990E
  • Juan José Arboleda <soyjuanarbol@gmail.com> 61FC681DFB92A079F1685E77973F295594EC4689
  • Julien Gilli <jgilli@fastmail.fm> 114F43EE0176B71C7BC219DD50A3051F888C628D
  • Rod Vagg <rod@vagg.org> DD8F2338BAE7501E3DD5AC78C273792F7D83545D
  • Ruben Bridgewater <ruben@bridgewater.de> A48C2BEE680E841632CD4E44F07496B3EB3C1762
  • Shelley Vohr <shelley.vohr@gmail.com> B9E2F5981AA6E0CD28160D9FF13993A75599653C
  • Timothy J Fontaine <tjfontaine@gmail.com> 7937DFD2AB06298B2293C3187D33FF9D0246406D

Security release stewards

When possible, the commitment to take slots in the security release steward rotation is made by companies in order to ensure individuals who act as security stewards have the support and recognition from their employer to be able to prioritize security releases. Security release stewards manage security releases on a rotation basis as outlined in the security release process.

Что такое Node.js: для чего нужен, преимущества и как установить

Abstract links

Node.js — это программная среда на JavaScript-движке (V8). Используется для компиляции JS-кода в машинный язык. Другими словами, эта программная платформа транслирует исходный JS непосредственно в машинный код, который и будет исполняться уже на серверной стороне.

Важно уточнить: Node.js не является самостоятельным языком программирования, это только программная платформа для использования JavaScript на серверной стороне. При этом она использует подходы событийно-ориентированного и так называемого реактивного программирования. Чаще всего, Node.js задействуется в качестве веб-сервера, также эта платформа может применяться и для создания десктопных программ и других целей (например, для программирования микроконтроллеров). Платформа Node.js появилась в 2009 году и сегодня используется очень широко, в самых разнообразных отраслях разработки. По типу программной платформы она относится к средам выполнения.

Простыми словами, Node.js — это платформа, которая умеет компилировать код JavaScript напрямую в машинный код. Таким образом достигается трансформация JavaScript из специализированного языка для браузера в язык программирования общего назначения.

Для чего нужен Node.js

Сперва проясним два важных момента: что такое Node и чем он не является.

Чем НЕ является Node

      • Это не фреймворк, это сервер.
      • Обертки Node над JavaScript V8 Runtime, сделаны не на JavaScript, а на языке C.
      • Node.js не многопоточный, он работает в одном потоке с обратным вызовом.
      • Node.js не подойдет для начинающих, кто не умеет работать с JavaScript.

    Чем является Node

        • Это сервер, который может выполнять JavaScript. Это своего рода браузер на стороне сервера.
        • Это кросс-платформа, подходящая для развертывания веб-приложений реального времени.
        • Node.js предоставляет вам асинхронные API, управляемые событиями типа ввод-вывод.
        • Node.js запускает однопоточный цикл, основанный на событиях, поэтому все вызовы становятся неблокирующими.

      Платформа Node.js используется для программирования на стороне сервера. Чаще всего, её код используется для создания веб-приложений, сайтов и веб-страниц, кроме того Node.js применяется для запуска утилит командной строки.

      Программная платформа используется для любой бэкенд-разработки, которая связана с языком JavaScript. Но фронтендеры также используют эту платформу для решение своих задач.

      Вот краткий список примеров, что можно сделать на Node.js:

      • Десктопная программа для различных операционных систем, включая Windows, Linux, DOS, UNIX, macOS.
      • Кроссплатформенная программа.
      • Онлайн-сервис.
      • Социальная сеть.
      • Онлайн-игра.
      • Любой сайт.

      Преимущества и недостатки

      Давайте начнём с недостатков, так как ограничения особенно важны ещё на этапе выбора программной платформы. Вот они:

      Минусы

      • Node.js не обеспечивает масштабируемость. Для поддержки нужной производительности одного процессора может оказаться недостаточно; при этом платформа не предоставляет никакой возможности масштабирования для использования преимуществ многоядерности, обычно присутствующей в современном серверном оборудовании.
      • Работа с реляционной базой данных превращается в сильную головную боль, если вы используете Node.
      • Каждый раз при использовании в коде обратного вызова (колл-бэк) генерируются тонны вложенных обратных вызовов.
      • Без глубокого погружения и знания JavaScript можно столкнуться с концептуальной проблемой.
      • Node.js не подходит для задач, требующих больших затрат процессора. Он хорошо подходит только для непосредственного ввода-вывода (например, для веб-серверов).

      Плюсы

      Теперь — достоинства платформы Node.js, которые оценят как новички, так и программисты с опытом:

      • Асинхронный ввод-вывод, управляемый событиями, помогает в одновременной обработке запросов.
      • Один и тот же фрагмент кода можно использовать как на серверной, так и клиентской стороне.
      • Использует JavaScript, который легко выучить за несколько месяцев
      • Для Node.js существует менеджер модулей Npm. Там можно найти практически любой нужный пакет и он продолжает расти.
      • Активное и живое сообщество, с большим количеством кода, распространяемого через GitHub и другие площадки для разработчиков.

      И, конечно, углубляясь в Node.js вы продолжаете совершенствоваться в профессии бэкенд-разработчика: у нас также есть полноценный курс для тех кто хочет постигнуть профессию бэкенд-разработчик. За 3 месяца вы ознакомитесь со всеми важными технологиями (от Node.js и PHP до серверного JavaScript), которые нужны специалисту в 2023 году и даже получите несколько впечатляющих проектов для своего будущего портфолио.

      Где Node будет лучшим решением

      Вот несколько приложений или областей, где Node.js может стать наилучшим инструментом:

      WebSocket servers. Неблокирующая архитектура делает Node.js наилучшим инструментом для развертывания WebSosket-приложений или стриминг-приложений. Серверы чатов могут стать более эффективными, быстрыми и отлаженными, используя Node.js в качестве основы (ведь такие серверы работают в режиме реального времени, где скорость отклика и передачи данных особенно важны),

      Клиент для быстрой загрузки файлов. С помощью Node вы можете загружать несколько файлов одновременно. Это означает, что в один и тот же момент времени на сервере может находиться часть файла Primer1 и часть Primer2. Такой подход значительно ускоряет скорость загрузки файлов.

      Потоковая передача данных. Поскольку Node имеет дело с концепцией обратного вызова, ее можно задействовать и для потоковой передачи данных. Это может быть очень полезно для самых разнообразных целей, особенно для бизнеса (например, агрегаторы товаров получают результаты сразу из нескольких сторонних API).

      Рекламный сервер. Рекламные серверы должны быть самыми быстрыми. Если реклама на сайте загружается быстрее чем основной контент, то главное внимание пользователя получит именно рекламный баннер. Другое дело, если реклама загружается медленнее: допустим, у вас большой баннер до контента, который загружается 5 секунд. И пока такая реклама будет прогружаться пользователь уже начнёт читать середину страницы. Поэтому рекламные серверы действительно должны быть быстрыми, и вот почему на них нужно использовать Node.

      Программное обеспечение для фондовой биржи. Это конкретный пример,хорошо иллюстрирующий возможности Node.js. В случае обновления акций все должно происходить в режиме реального времени. Node делает возможным развертывание веб-приложений, которые эффективно обмениваются данными в режиме реального времени.

      Как установить Node.js

      Сперва о Npm (сокр. от Node Package Manager) — это менеджер пакетов, устанавливающийся вместе с Node. Npm позволяет делиться своими пакетами и импортировать чужие пакеты для разработки своих приложений. Кроме того, Npm функционирует как утилита командной строки для установки пакетов в проект, управления зависимостями и другими параметрами.

      Компоненты Npm

      • Сайт: вы можете найти пакеты для своего проекта на официальном сайте Npm. Кроме того, вы можете создавать и настраивать профили для управления всеми типами проектов (и настройки к ним доступа).
      • Интерфейс командной строки (CLI): нужен для взаимодействия с пакетами и репозиториями Npm. Используется CLI, запускаемый с терминала.
      • Реестр: Имеет огромную базу данных проектов JavaScript и мета-данных. Позволяет использовать любой поддерживаемый Npm-реестр.

      Как скачать и установить Node.js и Npm на операционную систему Windows?

      Поскольку далее мы будем делать полноценное веб-приложение с помощью Node.js, прежде всего, необходимо установить саму платформу Node.js. На официальном сайте можно найти эту программную платформу для большинства операционных систем, включая Windows и Mac OS. В рамках этой статьи мы рассмотрим установку только на Windows.

      Давайте начнем с первого шага — установки программы.

      Шаг 1: Скачайте программу установки

      Скачайте программу установки для Windows с официального сайта Node.js. Убедитесь, что вы скачали последнюю версию. Она также включает в себя менеджер пакетов Npm.

      Обязательно выберите 64-битную версию программы установки

      Обязательно выберите 64-битную версию программы установки

      Рекомендуем выбрать LTS-версию (Long-term Support), если планируете использовать эту программную платформу долгосрочно. После клика по зеленой кнопке файл .msi будет загружен в ваш браузер.

      После загрузки установочного пакета на жёсткий диск — запустите его.

      Сделайте двойной клик по скаченному файлу

      Сделайте двойной клик по скаченному файлу

      Шаг 2: Установите программу Node.js и программу Npm

      Нажмите кнопку Next

      Нажмите кнопку Next

      На экране появится приветственное сообщение, нажмите кнопку «Далее» (или Next). Начнется процесс установки. Выберите нужный путь, куда вы хотите установить Node.js.

      Нажав на кнопку Next, вы попадёте на следующий экран настройки

      Нажав на кнопку Next, вы попадёте на следующий экран настройки

      Убедитесь, что вы выбрали менеджер пакетов npm, а не установленный по умолчанию Node.js runtime. Таким образом, мы сможем установить Node и Npm одновременно.

      Отметьте компоненты, которые должны быть установлены

      Отметьте компоненты, которые должны быть установлены

      У вас должно быть, как минимум, 143 мегабайт пространства для установки Node.js и функций npm.

      Убедитесь, что устанавливаете программу из под учетной записи администратора

      Убедитесь, что устанавливаете программу из под учетной записи администратора

      Теперь нажимаем кнопку Install. Ждём пока распакуются все файлы и установка будет завершена.

      Шаг 3: Проверьте текущую версию установленного Node.js и Npm

      Если у вас есть сомнения, правильно ли вы все установили или нет, можно проверить версию с помощью командной строки.

      Запустите командную строку «Нод»

      Запустите Node.js в командной строке

      На экране появится окно командной строки (Command Prompt). Проверьте версии Node.js и Npm с помощью команд:

      • node -v.
      • npm -v.

      Все установлено правильно


      Все установлено правильно

      Не стоит беспокоиться, если вы увидите цифры, отличные от тех, которые есть на скриншоте выше: Node и Npm очень часто обновляются. Главное — чтобы не было ошибок.

      Как пользоваться, основные команды

      Разобрать все возможности, функции и инструменты программной платформы Node.js было бы нереально в рамках одной статьи. Поэтому, далее — мы рассмотрим только основы: консоль / REPL, главные команды, синтаксис.

      Основы Node.js: синтаксис, типы примитивов, команды

      Node.js имеет полную совместимость с JavaScript (если можно вообще так выразиться). Таким образом, синтаксис JavaScript, который используется внутри Node.js аналогичен синтаксису браузерного JS.

      Мы сэкономим ваше время — приводим таблицу самых популярных команд Node.js, которая поможет вам начать работу с платформой:

      Используется для печати версии узла.

      Используется для печати опций командной строки узла.

      Воспринимает следующий аргумент как строку JavaScript. Модули, предопределенные в REPL, также могут быть использованы в сценарии.

      Он идентичен -e, но печатает результат выполнения кода.

      Проверяет синтаксис сценария без выполнения.

      Открывает REPL для интерактивной работы.

      -r, —require module

      Используется для предварительной загрузки указанного модуля при запуске. Он следует правилам разрешения модуля require(). Параметр module может быть либо путем к файлу, либо именем модуля узла.

      Отменяет предупреждения об устаревании.

      Выполняет печать трассировки стека для исправлений.

      Выбрасывает ошибки, связанные с устареванием.

      Отменяет вывод всех предупреждений.

      Печатает трассировку стека для предупреждений процесса (в том числе об устаревании).

      Печатает трассировку стека всякий раз, когда после обработки цикла событий обнаруживается синхронная операция ввода-вывода.

      Автоматически обнуляет все вновь выделенные экземпляры буферов.

      Отслеживает выделение объектов в куче.

      Обрабатывает вывод профилировщика V8, сгенерированный с помощью опции v8 —prof.

      Печатает параметры командной строки V8.

      Определяет альтернативный список TLS-сертификатов. По умолчанию Node.js собирается с поддержкой шифрования.

      Включает FIPS-совместимое шифрование при запуске (требуется, чтобы Node.js был собран с ./configure —openssl-fips).

      Принудительно включает FIPS-совместимое шифрование при запуске (нельзя отключить из кода скрипта). Те же требования, что и для ключа —enable-fips).

      Указывает путь загрузки данных ICU (Отменяет node_icu_data).

      Понимать все, что здесь написано, не обязательно. Просто сохраните эту таблицу как заметку — она точно понадобится вам позже.

      Давайте посмотрим на особенности программной платформы Node.js и узнаем, чем она отличается от браузерного JavaScript.

      Примитивы

      Node.js включает следующие типы примитивов:

      • Строка.
      • Число.
      • Булево.
      • Неопределенный.
      • Null.
      • RegExp.

      Все остальное — является объектом в Node.js.

      Динамическая типизация

      JS в Node.js имеет поддержку динамической типизации, как и в браузерном JS. Можно применять привычные операторы let, var и const для введения какой-либо переменной любого типа.

      Объектный литерал

      Синтаксис объектного литерала такой же, как и в браузерном JS.

      Функции

      Функция также может иметь атрибуты и свойства. Она может рассматриваться как класс в JavaScript.

      Buffer

      Node включает дополнительный тип данных под названием Buffer, который недоступен в браузерном JS. Буфер, в основном, используется для хранения двоичных данных, при чтении из файла или получении пакетов по сети.

      Объект процесса

      Каждый сценарий Node выполняется в процессе. Соответственно, в состав платформы включен объект process — для вывода деталей по конкретному процессу.

      В примере ниже показано, как в REPL получить информацию о процессе в REPL с помощью объекта process.

      По умолчанию локальный

      JavaScript Node отличается от браузерного JS и когда речь заходит о глобальной видимости. В браузерном JS переменные всегда приобретают статус глобальных. В Node по умолчанию все становится локальным.

      Доступ к глобальной области видимости

      В браузере глобальная область видимости — это объект окна (window). В Node за глобальную область видимости отвечает объект global.

      Чтобы добавить что-то в глобальную область видимости, нужно экспортировать это с помощью export (либо, для конкретных целей, введением module.export). Таким же образом импортируйте модули / объекты с помощью функции require(), чтобы получить к ним доступ из глобальной области видимости.

      Например, чтобы экспортировать объект в Node, нужно применить exports.name = object.

      Теперь вы можете импортировать объект log через функции require() и использовать его в любом месте вашего проекта.

      REPL: что это и как пользоваться

      Node поставляется с виртуальной средой REPL (она же оболочка или командная строке). REPL — это быстрый и простой способ тестирования кода Node / JavaScript.

      Node js javascript runtime что это

      CAPWAP (Control and Provisioning of Wireless Access Points) is a protocol that enables an access controller to manage a .

      Network performance monitoring (NPM) is the process of measuring and monitoring the quality of service of a network.

      Infrared radiation (IR), sometimes referred to simply as infrared, is a region of the electromagnetic radiation spectrum where .

      In computing, a logon is a procedure that enables an entity to access a secure system such as an operating system, application, .

      Security analytics is a cybersecurity approach that uses data collection, data aggregation and analysis tools for threat .

      The NICE Framework (National Initiative for Cybersecurity Education Cybersecurity Workforce Framework) is a reference resource .

      The prototyping model is a systems development method in which a prototype is built, tested and then reworked as necessary until .

      A digital ecosystem is a group of interconnected information technology resources that can function as a unit.

      A procurement plan — also called a procurement management plan — is a document that is used to manage the process of finding .

      A talent pipeline is a pool of candidates who are ready to fill a position.

      Recruitment process outsourcing (RPO) is when an employer turns the responsibility of finding potential job candidates over to a .

      A human resources generalist is an HR professional who handles the daily responsibilities of talent management, employee .

      Outbound marketing is a traditional form of marketing in which an organization initiates contact with potential customers, or .

      Churn rate is a measure of the number of customers or employees who leave a company during a given period.

      Marketing campaign management is the planning, executing, tracking and analysis of direct marketing campaigns.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *