Node js server side javascript adobe что это

Обновлено: 05.07.2024

Welcome to the Community!

We have a brand new look! Take a tour with us and explore the latest updates on Adobe Support Community.

Adobe Support Community

/t5/photoshop-ecosystem-discussions/can-i-turn-off-node-js-server-side-javascript/td-p/8731592 Nov 29, 2016 Nov 29, 2016

Copy link to clipboard

I have Node.js: Server-side JavaScript installed in C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs

I am on a data cap plan for my internet access and whenever I go over 3Gb, 5Gb, and 10Gb my monthly cost goes up by $10.00, then $15.00, and then another $15.00.

The Server-side JavaScript app has used up 2,160MB in just the last 10 days. This is running up my usage and more than doubling my monthly subscription costs to CC.

What is Server-side JavaScript actually doing?

Can I somehow disable or delete Server-side JavaScript?

Can I turn it off somehow and only run it once a month?

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

1 Correct answer

Another update on my problem.I have finally been able to get high speed DSL at my house. Bell upgraded their equipment at the local switching station and I was at their office to sign up before they even got the last wires hooked up. I've been dreaming about this ever since I moved into this house in 2000.I now have unlimited data so I turned node back on again. I still don't know what it does or why I have 3 versions of it installed but just in case it does something important I guess I'll just.

Copy link to clipboard

i don't know what it does but people have turned it off/renamed it and reported no problems noticed.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

Thanks kglad for your help. If I don't get any more replies to my question here I will try that. I have read that renaming it can cause error messages to pop up when you open Photoshop. Better than paying for all that extra data usage every month though.

As an update to my original post, I noticed that I have 2 instances of Node.js: Server-side JavaScript installed.

This is the one that keeps downloading 200 to 400MB of whatever every day. That's the one I want to get rid of.

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs

This one doesn't even download 1 MB per day.

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCLibrary\libs

Neither one of these show up in Windows 10 under "Apps and Features" or in Control Panel "Programs and Features" so I don't know how to even uninstall them if that's what I need to do. You also mention that some people have turned it off. How do you go about doing that?

I'm running Photoshop CC 2017 by the way.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

Yesterday alone the Node:js Server-side JavaScript in the C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs folder downloaded 419.76 MB of something? Remember that I have to start paying extra if I go over 3GB per month. So far in this months billing cycle it has downloaded 3398.19 MB (3.32 GB) and I'm only half way through the billing cycle. At this rate if I some how managed not to use any other data, Node alone is going to cost me $60.00 plus tax for the month. That is just not acceptable. Please Adobe, do something about this.

As a temporary fix to stop this data download I've re-named Node:js but just left it in the same folder. This morning I've not had the data download as on other days. I opened Photoshop and got no errors popping up. So far so good, but what does not having Node running do to Photoshop CC staying up to date, if that's what Node was actually doing?

I'd appreciate any more advice and help on this, especially from Adobe.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

you can always manually check for photoshop updates. they aren't released very often and i'm not aware of any that are critical.

ie, updates add new features or more camera raw support or fix bugs. i don't remember any related to security.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

If you don't have a need for Cloud based storage for libraries or are not involved in collaborations with other people then why not simply logout of Creative Cloud via the desktop app or through Photoshop itself under the 'Help' menu. You only need to login once a month to verify your account otherwise you don't even need to have internet access at all. You could also turn off 'syncing' in the desktop application as that will waste money by needlessly uploading library content to the cloud. Also under preferences go to plugins and make sure the box that says something like allow extensions to connect to the internet is not checked.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

Thanks Terri for your advice and help.

I wasn’t doing any Cloud based storage or collaborations and had never set that up so it should not have been generating any internet usage. I did have Syncing turn on but hadn’t told it to sync anything. My “Creative Cloud Files” folder in Windows “File Explorer” was empty. I have now turned it off as per your suggestion. In Photoshop under Edit/Preferences/Plug-ins I did have “Allow Extensions to Connect to the Internet” checked. I have now un-checked that.

I’m also going to try turning off the Creative Cloud desktop app and only run it once a month.

Ever since I renamed Node.exe in the “C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs” folder the daily downloads have stopped and Photoshop still works without any errors popping up. I still have another instance off Node.exe running in C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCLibrary\libs but it only generates less than 1MB of traffic per day so I just left it alone. I have a third instance of Node.exe in C:\Program Files\Adobe\Adobe Photoshop CC 2017 but I can’t tell if it’s using up any network resources so I left it alone.

So that is 3 versions of Node.exe.

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs (now disabled by changing the name)

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCLibrary\libs

C:\Program Files\Adobe\Adobe Photoshop CC 2017

I still have some questions about Node.exe.

Will renaming and therefore disabling the one Node.exe cause any problems latter on?

What does renaming an executable file do to the registry?

Does Creative Cloud need it to run for some reason? I would think Adobe installed it for a good reason.

If I really don’t need it then how can I uninstall it completely?

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

I just opened Photoshop and under the Help Menu I told it to Sign Out. A window popped up stating that this will disable Photoshop and Lightroom on this device. I said OK and when I tried to open a photo in Photoshop it told me that I had to sign in to be able to use it.

So I guess that means I can't stay signed out and still use Photoshop? I can be without internet access for a month but I can't be signed out.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

I don't know what the consequences are of renaming 'node.exe', but it's bound to interfere with contacting the Adobe servers. My apologies, I was wrong about signing out as that is the equivalent of deactivating, which slipped my mind -so you don't have a problem there. So what to try instead? Well you could just turn off your router of disable your network card, but a more elegant way would be to block Photoshop and maybe node.exe at your firewall with a firewall rules, then monitoring Task Manager or Activity Monitor for network activity..

I'm very puzzled exactly why you are getting so much network activity if you are not syncing libraries! Try disabling the Creative Cloud startup processes in Task Manager or the equivalent on a Mac-you may not have all of them. As you can see I keep most of them active, but as you can launch the desktop app manually not much is lost by deactivating them at startup. Also your computer will probably start quicker when these things are deactivated.

Adobe.jpg

If you want to experiment with blocking at the firewall, I would recommend Windows Firewall control which is free and easier than going into the firewall itself and making changes to firewall rules.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

Sorry for taking so long to respond. I was out of town for a few days and busy with other things.

Obviously I can’t turn off my router as I need to be connected for other reasons. As for blocking Photoshop and/or node.exe at my firewall, wouldn’t that then have the same effect as renaming node.exe and thereby interfere with contacting the Adobe servers? (If that's what node.exe does?)

Ever since I renamed Node.exe in the C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs folder I have not had any of the daily downloads of 300 – 400MB of data. It also does not appear to have interfered with any Adobe CC updates as I checked the CC desktop app 4 days ago and there where updates available for Camera Raw and Lightroom and this morning there was an update available for Photoshop.

I’d like to keep my startup processes at their default settings if I can.

I am totally puzzled as well as to why I was getting so much download network activity and syncing libraries was not enabled. What was being downloaded every day? And why do I have 3 instances of node.exe installed on my system?

Terri, can I ask you to check your system and see if you have node.exe installed in these locations as well?

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCLibrary\libs

C:\Program Files\Adobe\Adobe Photoshop CC 2017

Thanks for your help and thanks for the link to Windows Firewall Control.

Welcome to the Community!

We have a brand new look! Take a tour with us and explore the latest updates on Adobe Support Community.

Adobe Support Community

Auto-suggest helps you quickly narrow down your search results by suggesting possible matches as you type.
  • Home
  • Photoshop ecosystem
  • Discussions
  • Can I turn off Node.js: Server-side JavaScript
/t5/photoshop-ecosystem-discussions/can-i-turn-off-node-js-server-side-javascript/td-p/8731592 Nov 29, 2016 Nov 29, 2016

Copy link to clipboard

I have Node.js: Server-side JavaScript installed in C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs

I am on a data cap plan for my internet access and whenever I go over 3Gb, 5Gb, and 10Gb my monthly cost goes up by $10.00, then $15.00, and then another $15.00.

The Server-side JavaScript app has used up 2,160MB in just the last 10 days. This is running up my usage and more than doubling my monthly subscription costs to CC.

What is Server-side JavaScript actually doing?

Can I somehow disable or delete Server-side JavaScript?

Can I turn it off somehow and only run it once a month?

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

1 Correct answer

Another update on my problem.I have finally been able to get high speed DSL at my house. Bell upgraded their equipment at the local switching station and I was at their office to sign up before they even got the last wires hooked up. I've been dreaming about this ever since I moved into this house in 2000.I now have unlimited data so I turned node back on again. I still don't know what it does or why I have 3 versions of it installed but just in case it does something important I guess I'll just.

Copy link to clipboard

i don't know what it does but people have turned it off/renamed it and reported no problems noticed.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

Thanks kglad for your help. If I don't get any more replies to my question here I will try that. I have read that renaming it can cause error messages to pop up when you open Photoshop. Better than paying for all that extra data usage every month though.

As an update to my original post, I noticed that I have 2 instances of Node.js: Server-side JavaScript installed.

This is the one that keeps downloading 200 to 400MB of whatever every day. That's the one I want to get rid of.

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs

This one doesn't even download 1 MB per day.

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCLibrary\libs

Neither one of these show up in Windows 10 under "Apps and Features" or in Control Panel "Programs and Features" so I don't know how to even uninstall them if that's what I need to do. You also mention that some people have turned it off. How do you go about doing that?

I'm running Photoshop CC 2017 by the way.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

Yesterday alone the Node:js Server-side JavaScript in the C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs folder downloaded 419.76 MB of something? Remember that I have to start paying extra if I go over 3GB per month. So far in this months billing cycle it has downloaded 3398.19 MB (3.32 GB) and I'm only half way through the billing cycle. At this rate if I some how managed not to use any other data, Node alone is going to cost me $60.00 plus tax for the month. That is just not acceptable. Please Adobe, do something about this.

As a temporary fix to stop this data download I've re-named Node:js but just left it in the same folder. This morning I've not had the data download as on other days. I opened Photoshop and got no errors popping up. So far so good, but what does not having Node running do to Photoshop CC staying up to date, if that's what Node was actually doing?

I'd appreciate any more advice and help on this, especially from Adobe.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

you can always manually check for photoshop updates. they aren't released very often and i'm not aware of any that are critical.

ie, updates add new features or more camera raw support or fix bugs. i don't remember any related to security.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

If you don't have a need for Cloud based storage for libraries or are not involved in collaborations with other people then why not simply logout of Creative Cloud via the desktop app or through Photoshop itself under the 'Help' menu. You only need to login once a month to verify your account otherwise you don't even need to have internet access at all. You could also turn off 'syncing' in the desktop application as that will waste money by needlessly uploading library content to the cloud. Also under preferences go to plugins and make sure the box that says something like allow extensions to connect to the internet is not checked.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

Thanks Terri for your advice and help.

I wasn’t doing any Cloud based storage or collaborations and had never set that up so it should not have been generating any internet usage. I did have Syncing turn on but hadn’t told it to sync anything. My “Creative Cloud Files” folder in Windows “File Explorer” was empty. I have now turned it off as per your suggestion. In Photoshop under Edit/Preferences/Plug-ins I did have “Allow Extensions to Connect to the Internet” checked. I have now un-checked that.

I’m also going to try turning off the Creative Cloud desktop app and only run it once a month.

Ever since I renamed Node.exe in the “C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs” folder the daily downloads have stopped and Photoshop still works without any errors popping up. I still have another instance off Node.exe running in C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCLibrary\libs but it only generates less than 1MB of traffic per day so I just left it alone. I have a third instance of Node.exe in C:\Program Files\Adobe\Adobe Photoshop CC 2017 but I can’t tell if it’s using up any network resources so I left it alone.

So that is 3 versions of Node.exe.

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs (now disabled by changing the name)

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCLibrary\libs

C:\Program Files\Adobe\Adobe Photoshop CC 2017

I still have some questions about Node.exe.

Will renaming and therefore disabling the one Node.exe cause any problems latter on?

What does renaming an executable file do to the registry?

Does Creative Cloud need it to run for some reason? I would think Adobe installed it for a good reason.

If I really don’t need it then how can I uninstall it completely?

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

I just opened Photoshop and under the Help Menu I told it to Sign Out. A window popped up stating that this will disable Photoshop and Lightroom on this device. I said OK and when I tried to open a photo in Photoshop it told me that I had to sign in to be able to use it.

So I guess that means I can't stay signed out and still use Photoshop? I can be without internet access for a month but I can't be signed out.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

I don't know what the consequences are of renaming 'node.exe', but it's bound to interfere with contacting the Adobe servers. My apologies, I was wrong about signing out as that is the equivalent of deactivating, which slipped my mind -so you don't have a problem there. So what to try instead? Well you could just turn off your router of disable your network card, but a more elegant way would be to block Photoshop and maybe node.exe at your firewall with a firewall rules, then monitoring Task Manager or Activity Monitor for network activity..

I'm very puzzled exactly why you are getting so much network activity if you are not syncing libraries! Try disabling the Creative Cloud startup processes in Task Manager or the equivalent on a Mac-you may not have all of them. As you can see I keep most of them active, but as you can launch the desktop app manually not much is lost by deactivating them at startup. Also your computer will probably start quicker when these things are deactivated.

Adobe.jpg

If you want to experiment with blocking at the firewall, I would recommend Windows Firewall control which is free and easier than going into the firewall itself and making changes to firewall rules.

Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more

Copy link to clipboard

Sorry for taking so long to respond. I was out of town for a few days and busy with other things.

Obviously I can’t turn off my router as I need to be connected for other reasons. As for blocking Photoshop and/or node.exe at my firewall, wouldn’t that then have the same effect as renaming node.exe and thereby interfere with contacting the Adobe servers? (If that's what node.exe does?)

Ever since I renamed Node.exe in the C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs folder I have not had any of the daily downloads of 300 – 400MB of data. It also does not appear to have interfered with any Adobe CC updates as I checked the CC desktop app 4 days ago and there where updates available for Camera Raw and Lightroom and this morning there was an update available for Photoshop.

I’d like to keep my startup processes at their default settings if I can.

I am totally puzzled as well as to why I was getting so much download network activity and syncing libraries was not enabled. What was being downloaded every day? And why do I have 3 instances of node.exe installed on my system?

Terri, can I ask you to check your system and see if you have node.exe installed in these locations as well?

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCXProcess\libs

C:\Program Files (x86)\Adobe\Adobe Creative Cloud\CCLibrary\libs

C:\Program Files\Adobe\Adobe Photoshop CC 2017

Thanks for your help and thanks for the link to Windows Firewall Control.

Мы начинаем публикацию серии материалов, которые представляют собой поэтапный перевод руководства по Node.js для начинающих. А именно, в данном случае «начинающий» — это тот, кто обладает некоторыми познаниями в области браузерного JavaScript. Он слышал о том, что существует серверная платформа, программы для которой тоже пишут на JS, и хотел бы эту платформу освоить. Возможно, вы найдёте здесь что-то полезное для себя и в том случае, если уже знакомы с Node.js.

Кстати, в прошлом году у нас был похожий по масштабам проект, посвящённый bash-скриптам. Тогда мы, после публикации всех запланированных материалов, собрали их в виде PDF-файла. Так же планируется поступить и в этот раз.


Сегодня мы обсудим особенности Node.js, начнём знакомство с экосистемой этой платформы и напишем серверный «Hello World».

Обзор Node.js

Node.js — это опенсорсная кроссплатформенная среда выполнения для JavaScript, которая работает на серверах. С момента выпуска этой платформы в 2009 году она стала чрезвычайно популярной и в наши дни играет весьма важную роль в области веб-разработки. Если считать показателем популярности число звёзд, которые собрал некий проект на GitHub, то Node.js, у которого более 50000 звёзд, это очень и очень популярный проект.

Платформа Node.js построена на базе JavaScript движка V8 от Google, который используется в браузере Google Chrome. Данная платформа, в основном, используется для создания веб-серверов, однако сфера её применения этим не ограничивается.

Рассмотрим основные особенности Node.js.

▍Скорость

Одной из основных привлекательных особенностей Node.js является скорость. JavaScript-код, выполняемый в среде Node.js, может быть в два раза быстрее, чем код, написанный на компилируемых языках, вроде C или Java, и на порядки быстрее интерпретируемых языков наподобие Python или Ruby. Причиной подобного является неблокирующая архитектура платформы, а конкретные результаты зависят от используемых тестов производительности, но, в целом, Node.js — это очень быстрая платформа.

▍Простота

Платформа Node.js проста в освоении и использовании. На самом деле, она прямо-таки очень проста, особенно это заметно в сравнении с некоторыми другими серверными платформами.

▍JavaScript

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

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

▍Движок V8

В основе Node.js, помимо других решений, лежит опенсорсный JavaScript-движок V8 от Google, применяемый в браузере Google Chrome и в других браузерах. Это означает, что Node.js пользуется наработками тысяч инженеров, которые сделали среду выполнения JavaScript Chrome невероятно быстрой и продолжают работать в направлении совершенствования V8.

▍Асинхронность

В традиционных языках программирования (C, Java, Python, PHP) все инструкции, по умолчанию, являются блокирующими, если только разработчик явным образом не позаботится об асинхронном выполнении кода. В результате если, например, в такой среде, произвести сетевой запрос для загрузки некоего JSON-кода, выполнение потока, из которого сделан запрос, будет приостановлено до тех пор, пока не завершится получение и обработка ответа.

JavaScript значительно упрощает написание асинхронного и неблокирующего кода с использованием единственного потока, функций обратного вызова (коллбэков) и подхода к разработке, основанной на событиях. Каждый раз, когда нам нужно выполнить тяжёлую операцию, мы передаём соответствующему механизму коллбэк, который будет вызван сразу после завершения этой операции. В результате, для того чтобы программа продолжила работу, ждать результатов выполнения подобных операций не нужно.

Подобный механизм возник в браузерах. Мы не можем позволить себе ждать, скажем, окончания выполнения AJAX-запроса, не имея при этом возможности реагировать на действия пользователя, например, на щелчки по кнопкам. Для того чтобы пользователям было удобно работать с веб-страницами, всё, и загрузка данных из сети, и обработка нажатия на кнопки, должно происходить одновременно, в режиме реального времени.

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

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

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

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

▍Библиотеки

Благодаря простоте и удобству работы с менеджером пакетов для Node.js, который называется npm, экосистема Node.js прямо-таки процветает. Сейчас в реестре npm имеется более полумиллиона опенсорсных пакетов, которые может свободно использовать любой Node.js-разработчик.
Рассмотрев некоторые основные особенности платформы Node.js, опробуем её в действии. Начнём с установки.

Установка Node.js

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

Существует ещё один весьма удобный способ установки Node.js, который заключается в использовании менеджера пакетов, имеющегося в операционной системе. Например, менеджер пакетов macOS, который является фактическим стандартом в этой области, называется Homebrew. Если он в вашей системе есть, вы можете установить Node.js, выполнив эту команду в командной строке:


Список менеджеров пакетов для других операционных систем, в том числе — для Linux и Windows, можно найти здесь.

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

Я посоветовал бы начинающим пользоваться официальными установщиками Node.js. Пользователям macOS я порекомендовал бы устанавливать Node.js с помощью Homebrew. Теперь, после того, как вы установили Node.js, пришло время написать «Hello World».

Первое Node.js-приложение

Самым распространённым примером первого приложения для Node.js можно назвать простой веб-сервер. Вот его код:


Для того чтобы запустить этот код, сохраните его в файле server.js и выполните в терминале такую команду:

Разберём этот пример.

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

Сервер настроен на прослушивание определённого порта на заданном хосте. Когда сервер будет готов, вызывается соответствующий коллбэк, сообщающий нам о том, что сервер работает.

Первый предоставляет в наше распоряжение сведения о запросе. В нашем простом примере этими данными мы не пользуемся, но, при необходимости, с помощью объекта req можно получить доступ к заголовкам запроса и к переданным в нём данным.

Второй нужен для формирования и отправки ответа на запрос.

В данном случае ответ на запрос мы формируем следующим образом. Сначала устанавливаем свойство statusCode в значение 200 , что указывает на успешное выполнение операции:


Далее, мы устанавливаем заголовок Content-Type :


После этого мы завершаем подготовку ответа, добавляя его содержимое в качестве аргумента метода end() :


Мы уже говорили о том, что вокруг платформы Node.js сформировалась мощная экосистема. Обсудим теперь некоторые популярные фреймворки и вспомогательные инструменты для Node.js.

Фреймворки и вспомогательные инструменты для Node.js

Node.js — это низкоуровневая платформа. Для того чтобы упростить разработку для неё и облегчить жизнь программистам, было создано огромное количество библиотек. Некоторые из них со временем стали весьма популярными. Вот небольшой список библиотек, которые я считаю отлично сделанными и достойными изучения:

Краткая история Node.js

В этом году Node.js исполнилось уже 9 лет. Это, конечно, не так уж и много, если сравнить этот возраст с возрастом JavaScript, которому уже 23 года, или с 25-летним возрастом веба, существующем в таком виде, в котором мы его знаем, если считать от появления браузера Mosaic.

9 лет — это маленький срок для технологии, но сейчас возникает такое ощущение, что платформа Node.js существовала всегда.

Я начал работу с Node.js с ранних версий платформы, когда ей было ещё только 2 года. Даже тогда, несмотря на то, что информации о Node.js было не так уж и много, уже можно было почувствовать, что Node.js — это очень серьёзно.

Теперь поговорим о технологиях, лежащих в основе Node.js и кратко рассмотрим основные события, связанные с этой платформой.

Итак, JavaScript — это язык программирования, который был создан в Netscape как скриптовый язык, предназначенный для управления веб-страницами в браузере Netscape Navigator.



Node.js это — среда выполнения JavaScript. Что же это значит, и как работает?
Окружение Node.js включает все, что вам нужно для выполнения программы, написанной на JavaScript.

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

Теперь вы можете сделать гораздо больше с JavaScript, чем просто интерактивные веб-сайты.

Теперь у JavaScript есть возможность делать то, что могут делать другие скриптовые языки программирования, такие как Python.

Оба — браузерный JavaScript и Node.js запускаются в среде выполнения V8. Этот движок использует ваш JS код, и преобразует его в более быстрый машинный код. Машинный – низкоуровневый код, который компьютер может запускать без необходимости сначала его интерпретировать.

Почему Node.js?


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

Мы уже обсуждали первую строку этого определения: «Node.js — среда выполнения JavaScript, основанная на JavaScript движке V8 из Chrome». Теперь давайте разбираться в двух других строках, так мы сможем понять, почему Node.js так популярен.

Рассмотрим сценарий, в котором мы запрашиваем user1 и user2 из бекенда, а затем печатаем их на экране / в консоли. Ответ на этот запрос требует времени, но оба запроса пользовательских данных могут выполняться независимо и в одно и то же время.

Блокирование ввода-вывода

В методе блокировки запрос данных user2 не запускается до тех пор, пока данные user1 не будут напечатаны на экране.

Если это был веб-сервер, нам нужно было бы начать новый поток для каждого нового пользователя. Но JavaScript однопоточен (но он имеет однопоточный цикл событий, о котором мы поговорим чуть позже). Таким образом, это сделает JavaScript не очень подходящим для многопоточных задач.

Неблокирующий ввод-вывод

С другой стороны, используя неблокирующий запрос, вы можете инициировать запрос данных для user2, не дожидаясь ответа на запрос user1. Вы можете инициировать оба запроса параллельно.

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

Цикл событий JavaScript

Если у вас есть 26 минут, посмотрите отличное видео-объяснение Node Event Loop:

Если нету, вот пошаговое объяснение того, как работает Event Loop в JavaScript:


1. Посылаете main() в стек вызовов.

2. Посылаете console.log() в стек вызовов. Он запускается сразу и появляется.

3. Посылаете setTimeout(2000) в стек. setTimeout(2000) это — Node API. Когда мы его вызываем, мы регистрируем пару событие-коллбек. Событие будет ждать 2000 миллисекунд, а потом вызовет коллбек.

4. После регистрации, setTimeout(2000) появляется в стеке вызовов.

5. Теперь второй setTimeout(0) регистрируется таким же образом. Теперь у нас есть два API-интерфейса Node, ожидающих выполнения.

6. После ожидания 0 секунд setTimeout(0) перемещается в очередь выполнения коллбеков (callback queue), и то же самое происходит с setTimeout(2000).

7. В очереди выполнения коллбеков функции ждут, когда стек вызовов будет пустым, потому что только одна функция может выполняться одновременно. Это обеспечивает event loop.

8. Вызывается последняя console.log(), а main() вызывается из стека вызовов.

9. Цикл событий видит, что стек вызовов пуст, а очередь обратного вызова — нет. Таким образом, он перемещает обратные вызовы (по порядку) в стек вызовов для выполнения.



Это библиотеки, построенные сообществом. Они решат большинство часто встречающихся проблем. npm (менеджер пакетов Node) содержит пакеты, которые вы можете использовать в своих приложениях, чтобы сделать вашу разработку более быстрой и эффективной.

Require

Require исполняет три функции:

Node модули

Node модули это — многоразово используемые блоки кода, существование которых не случайно не влияет на другой код.

Вы можете написать свои собственные модули и использовать их в различных приложениях. Node.js имеет набор встроенных модулей, которые вы можете использовать без специальной установки.

V8 ускоряет JavaScript, используя C ++

V8 – движок с открытым исходным кодом, написанный на C ++.

JavaScript -> V8 (C ++) -> машинный код

V8 реализует сценарий ECMAScript, как указано в ECMA-262. ECMAScript был создан Ecma International для стандартизации JavaScript.

V8 может работать автономно или может быть встроен в любое приложение C ++. Благодаря этому, вы можете написать свой собственный код на C ++, и сделать его доступным для JavaScript.

События

События – это все, что произошло в нашем приложении, и на что мы можем ответить.

Читайте также: