Как пользоваться node js
Перейти к содержимому

Как пользоваться node js

  • автор:

Node.js Guides

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.

Node.js v21.2.0 documentation

Please see the Command-line options document for more information.

Example #

An example of a web server written with Node.js which responds with ‘Hello, World!’ :

Commands in this document start with $ or > to replicate how they would appear in a user’s terminal. Do not include the $ and > characters. They are there to show the start of each command.

Lines that don’t start with $ or > character show the output of the previous command.

First, make sure to have downloaded and installed Node.js. See Installing Node.js via package manager for further install information.

Now, create an empty project folder called projects , then navigate into it.

mkdir ~/projects cd ~/projects 
mkdir %USERPROFILE%\projects cd %USERPROFILE%\projects 
mkdir $env:USERPROFILE\projects cd $env:USERPROFILE\projects 

Next, create a new source file in the projects folder and call it hello-world.js .

Open hello-world.js in any preferred text editor and paste in the following content:

const http = require('node: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://$ :$ /`); >); 

Save the file. Then, in the terminal window, to run the hello-world.js file, enter:

node hello-world.js 

Output like this should appear in the terminal:

Server running at http://127.0.0.1:3000/ 

Now, open any preferred web browser and visit http://127.0.0.1:3000 .

If the browser displays the string Hello, World! , that indicates the server is working.

Введение в Node JS

Node.js представляет среду выполнения кода на JavaScript, которая построена на основе движка JavaScript Chrome V8, который позволяет транслировать вызовы на языке JavaScript в машинный код. Node.js прежде всего предназначен для создания серверных приложений на языке JavaScript. Хотя также существуют проекты по написанию десктопных приложений (Electron) и даже по созданию кода для микроконтроллеров. Но прежде всего мы говорим о Node.js, как о платформе для создания веб-приложений.

Node.js является открытым проектом, исходники которого можно посмотреть на github.com.

Установка

Для загрузки перейдет на официальный сайт https://nodejs.org/en/. На главной странице мы сразу увидим две возможные опции для загрузки: самая последняя версия NodeJS и LTS-версия.

Загрузка NodeJS

Загрузим последнюю версию. В моем случае это версия 16.1.0. Для Windows установщик представляет файл с расширением msi. После запуска откроется программа установщика:

Установка Node JS на Windows

После успешной установки вы можем ввести в командной строке/терминале команду node -v , и нам отобразится текущая версия node.js:

C:\WINDOWS\system32>node -v v16.1.0

Версии node.js для других операционных систем наряду с исходниками можно найти по адресу https://nodejs.org/en/download/

Инструменты разработки

Для разработки под Node JS достаточно простейшего текстового редактора, в частности, Notepad++. Также можно использовать более изощренные редакторы типа Atom, Sublime, Visual Studio Code, либо среды разработки, которые поддерживают работу с Node.JS, например, Visual Studio или WebStorm.

REPL

После установки NodeJS нам становится доступным такой инструмент как REPL. REPL (Read Eval Print Loop) представляет возможность запуска выражений на языке JavaScript в командной строке или терминале.

Так, запустим командную строку (на Windows) или терминал (на OS X или Linux) и введем команду node . После ввода этой команды мы можем выполнять различные выражения на JavaScript:

C:\WINDOWS\system32>node Welcome to Node.js v16.1.0 Type ".help" for more information. > 2+6 8 >

Или используем какую-нибудь функцию JS:

> console.log("Hello NodeJS"); Hello NodeJS undefined >

Можно определять свои функции и затем их вызывать, например, возведение числа в квадрат:

> function square(x) undefined >square(5) 25 >

Если мы введем что-то неправильно, то REPL укажет об ошибке:

REPL in Node JS

Выполнение файла

Вместо того чтобы вводить весь код напрямую в консоль, удобнее вынести его во внешний файл. Например, создадим на жестком диске новый каталог, допустим, C:\node\helloapp , в который поместим новый файл app.js со следующим кодом:

console.log("Hello world");

В командной строке перейдем с помощью команды cd к каталогу helloapp, а затем выполним команду:

node app.js

Данная команда выполнит код из файла app.js:

Debug a Node.js server application

Node.js contains a built-in debugger that can interface with Chromium-based web browsers and popular IDEs such as Visual Studio Code and JetBrains WebStorm. Start the debugger by supplying the —inspect flag when running your server code.

node --inspect myApp.js

This will start a debugging server on 127.0.0.1:9229 . Follow the official instructions to connect to the server with your favourite browser or IDE.

If you do not want to debug through a browser or editor, you can use Node.js’s simple CLI-based debugger by running node inspect :

node inspect myApp.js

Type help for a list of debugging commands.

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

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