Javascript node js это

Introduction to Node.js

Getting started guide to Node.js, the server-side JavaScript runtime environment. Node.js is built on top of the Google Chrome V8 JavaScript engine, and it’s mainly used to create web servers — but it’s not limited to just that.

Node.js is an open-source and cross-platform JavaScript runtime environment. It is a popular tool for almost any kind of project!

Node.js runs the V8 JavaScript engine, the core of Google Chrome, outside of the browser. This allows Node.js to be very performant.

A Node.js app runs in a single process, without creating a new thread for every request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript code from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behavior the exception rather than the norm.

When Node.js performs an I/O operation, like reading from the network, accessing a database or the filesystem, instead of blocking the thread and wasting CPU cycles waiting, Node.js will resume the operations when the response comes back.

This allows Node.js to handle thousands of concurrent connections with a single server without introducing the burden of managing thread concurrency, which could be a significant source of bugs.

Node.js has a unique advantage because millions of frontend developers that write JavaScript for the browser are now able to write the server-side code in addition to the client-side code without the need to learn a completely different language.

In Node.js the new ECMAScript standards can be used without problems, as you don’t have to wait for all your users to update their browsers — you are in charge of deciding which ECMAScript version to use by changing the Node.js version, and you can also enable specific experimental features by running Node.js with flags.

Читайте также:  Get cookies by name in javascript

An Example Node.js Application

The most common example Hello World of Node.js is a web server:

To run this snippet, save it as a server.js file and run node server.js in your terminal.

This code first includes the Node.js http module.

Node.js has a fantastic standard library, including first-class support for networking.

The createServer() method of http creates a new HTTP server and returns it.

The server is set to listen on the specified port and host name. When the server is ready, the callback function is called, in this case informing us that the server is running.

Whenever a new request is received, the request event is called, providing two objects: a request (an http.IncomingMessage object) and a response (an http.ServerResponse object).

Those 2 objects are essential to handle the HTTP call.

The first provides the request details. In this simple example, this is not used, but you could access the request headers and request data.

The second is used to return data to the caller.

we set the statusCode property to 200, to indicate a successful response.

We set the Content-Type header:

and we close the response, adding the content as an argument to end() :

Источник

О Node.js®

Как асинхронное событийное JavaScript-окружение, Node.js спроектирован для построения масштабируемых сетевых приложений. Ниже приведен пример «hello world», который может одновременно обрабатывать много соединений. Для каждого соединения вызывается функция обратного вызова, однако, когда соединений нет Node.js засыпает.

const http = require("http"); const hostname = "127.0.0.1"; const port = 3000; const server = http.createServer((req, res) => < res.statusCode = 200; res.setHeader("Content-Type", "text/plain"); res.end("Hello World\n"); >); server.listen(port, hostname, () => < console.log(`Server running at http://$:$/`); >); 

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

Для более детального знакомства с этим подходом, можно ознакомится с полной статьей Blocking vs Non-Blocking.

Node.js создан под влиянием таких систем как Event Machine в Ruby или Twisted в Python. Но при этом событийная модель, в нем, используется значительно шире, принимая event loop за основу окружения, а не в качестве отдельной библиотеки. В других системах всегда происходят блокировки вызова, чтобы запустить цикл событий.

Обычно, поведение определяется через функции обратного вызова (callback) в начале скрипта и дальнейшим его вызовом через блокирующий вызов, вроде EventMachine::run() . В Node.js нет ничего похожего на вызов начала цикла событий, он автоматически входит в него после запуска скрипта. Node.js выходит из событийного цикла тогда, когда не остается зарегистрированных функций обратного вызова. Такое поведение похоже на поведение браузерного JavaScript, где событийный цикл скрыт от пользователя.

HTTP является объектом первого рода в Node.js, разработанным с поточностью и малой задержкой, что делает Node.js хорошей основой для веб-библиотеки или фреймворка.

То что Node.js спроектирован без многопоточности, не означает, что в нем нет возможности использовать нескольких ядер. Для работы с ними можно создавать и управлять дочерними процессами, с помощью API Child_process.fork() . Модуль cluster построен на этом интерфейсе и позволяет делиться сокетами между процессами и распределять нагрузку между ядрами.

Copyright OpenJS Foundation and Node.js contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.

Источник

About Node.js®

As an asynchronous event-driven JavaScript runtime, Node.js is designed to build scalable network applications. In the following «hello world» example, many connections can be handled concurrently. Upon each connection, the callback is fired, but if there is no work to be done, Node.js will sleep.

const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => < res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World'); >); server.listen(port, hostname, () => < console.log(`Server running at http://$:$/`); >); 

This is in contrast to today’s more common concurrency model, in which OS threads are employed. Thread-based networking is relatively inefficient and very difficult to use. Furthermore, users of Node.js are free from worries of dead-locking the process, since there are no locks. Almost no function in Node.js directly performs I/O, so the process never blocks except when the I/O is performed using synchronous methods of Node.js standard library. Because nothing blocks, scalable systems are very reasonable to develop in Node.js.

If some of this language is unfamiliar, there is a full article on Blocking vs. Non-Blocking.

Node.js is similar in design to, and influenced by, systems like Ruby’s Event Machine and Python’s Twisted. Node.js takes the event model a bit further. It presents an event loop as a runtime construct instead of as a library. In other systems, there is always a blocking call to start the event-loop. Typically, behavior is defined through callbacks at the beginning of a script, and at the end a server is started through a blocking call like EventMachine::run() . In Node.js, there is no such start-the-event-loop call. Node.js simply enters the event loop after executing the input script. Node.js exits the event loop when there are no more callbacks to perform. This behavior is like browser JavaScript — the event loop is hidden from the user.

HTTP is a first-class citizen in Node.js, designed with streaming and low latency in mind. This makes Node.js well suited for the foundation of a web library or framework.

Node.js being designed without threads doesn’t mean you can’t take advantage of multiple cores in your environment. Child processes can be spawned by using our child_process.fork() API, and are designed to be easy to communicate with. Built upon that same interface is the cluster module, which allows you to share sockets between processes to enable load balancing over your cores.

Copyright OpenJS Foundation and Node.js contributors. All rights reserved. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them.

Источник

Оцените статью