Ebben a cikkben néhány hatékony eszközzel foglalkozunk, amelyek segítenek megtalálni és kijavítani a hibákat a VSCode, a Docker és a terminál használatával. Megtanuljuk (és a gyakorlatban is megtanuljuk) a Node.js alkalmazás 6 hibakeresési módját.
Kitalálhatja, mi a Node.js alkalmazás hibakeresésének 6 lehetséges módja? Minden fejlesztő életében az egyik leggyakoribb gyakorlat magában foglalja a hibák gyors megtalálását és annak megértését, hogy mi zajlik az alkalmazásaikban.
Az itt bemutatott legtöbb példa a Node.js fájlt fogja használni, de felhasználhatja a JavaScript kezelőfelületein is. Használhat más szerkesztőket vagy IDE-ket, mint például a Visual Studio vagy a Web Storm, de ebben a bejegyzésben a VSCode-ot fogom használni. Csak vegye be az itt tanultakat, és alkalmazza a választott szerkesztőben.
A bejegyzés végére megtanulhatja, hogyan ellenőrizheti alkalmazásait a következő eszközök használatával:
- Node.js Read-Eval-Print-Loop (REPL)
- Böngésző
- Dokkmunkás
- VSCode és helyi környezet
- VSCode és Docker
- VSCode és távoli környezet
Követelmények
A következő lépésekben létrehoz egy webes API-t a Node.js használatával, és hibakeresését végzi az alkalmazás VSCode és Docker használatával. A kódolás megkezdése előtt ellenőrizze, hogy a következő eszközök vannak-e telepítve a gépére:
- Dokkmunkás
- Node.js v14
- VSCode
Bevezetés
Ha egy ideje fejlesztőként dolgozol, akkor tudhatod, hogy ez nem olyan, mint a filmekben. Valójában a fejlesztőknek munkájuk 80% -át gondolkodásra kell fordítaniuk, és csak 20% -ot kell kódra írni.
De a valóságban ennek a 80% -nak a legnagyobb részét a problémák megoldása, a hibák kijavítása és a további problémák elkerülésének megkísérlése fordítja. Péntek este az alábbi GIF-nek tűnhet:
Amikor rájövök, hogy valami furcsa történt a munkám során, megpróbálok feltenni néhány kérdést, amint az a következő szakaszokban láthatja.
Helyesírási hiba volt?
Ebben az esetben a probléma valamilyen függvénnyel vagy változóval lehet, amelyet megpróbálok meghívni. A konzol megmutatja, hol van a hiba, és egy rövid lehetséges okot a hiba eldobására, az alábbi nyomtatás szerint:

Ez a viselkedés működnie kellene a jelenlegi megvalósítással?
Ez lehet egy if utasítás, amely nem értékelte a feltételeimet, vagy akár egy ciklus, amelynek bizonyos interakciók után meg kell állnia, de nem áll le.
Mi történik itt?
Ebben az esetben lehet belső hiba, vagy valami, amit még soha nem láttam. Tehát google-olom, hogy rájöjjek, mi történt a jelentkezésemben.
Például az alábbi kép egy belső Node.js adatfolyam hibát mutat, amely nem azt mutatja, hogy mit csináltam rosszul a programomban.

A szkriptalapú nyelvek hibakeresése
Általában a szkriptalapú nyelvek, például a Ruby, a Python vagy a JavaScript fejlesztőinek nem kell használniuk az IDE-ket, mint például a Visual Studio, a WebStorm és így tovább.
Ehelyett gyakran olyan könnyű szerkesztők mellett döntenek, mint a Sublime Text, VSCode, VIM és mások. Az alábbi kép az alkalmazások ellenőrzésének és "hibakeresésének" bevett gyakorlatát mutatja. Nyilatkozatokat nyomtatnak az alkalmazás állapotainak és értékeinek ellenőrzésére.

Elkezdeni
Az a gyakorlat, amelyet az előző szakaszban megnéztünk, nem olyan eredményes, mint lehet. Összekeverhetjük a szövegneveket az értékekkel, hibás változókat nyomtathatunk ki, és időt pazarolhatunk egyszerű hibákra vagy helyesírási hibákra. A következő szakaszokban bemutatom más módszereket a hibák és az állítások ellenőrzésének javítására.
A fő cél itt bemutatni, hogy mennyire egyszerű egy alkalmazás hibakeresése. A leggyakoribb eszközök használatával ellenőrizheti a kódokat az egyszerű terminálparancsoktól a távoli gépekig a világ minden tájáról.
A minta projekt létrehozása
Mielőtt elmélyülnénk a hibakeresési koncepciókban, létre kell hoznia egy alkalmazást az ellenőrzéshez. Tehát először hozzon létre egy Web API-t a natív Node.js HTTP modul használatával. Az API-nak meg kell kapnia a kérelem összes mezőjét, összesítenie kell az összes értéket belőle, majd válaszolnia kell a kérelmezőnek a kiszámított eredményekkel.
Válasszon egy üres mappát a gépén, és kezdjük a Web API-val.
Először hozzon létre egy Math.js
fájlt, amely a JavaScript objektum összes mezőjének összegzéséért felel:
//Math.js module.exports = { sum(...args) { return args.reduce( (prev, next) => Number(prev) + Number(next), 0 ) } }
Másodszor hozzon létre egy Node.js szerverfájlt az alábbi kód használatával. Másolja az értéket, és hozza létre a fájlt, majd illessze be oda. Később elmagyarázom, mi történik ott.
Figyelje meg, hogy ez az API eseményvezérelt API, és a kérelmeket a Node.js adatfolyam-megközelítés használatával kezeli.
//server.js const Http = require('http') const PORT = 3000 const { promisify } = require('util') const { pipeline } = require('stream') const pipelineAsync = promisify(pipeline) const { sum } = require('./Math') let counter = 0 Http.createServer(async (req, res) => { try { await pipelineAsync( req, async function * (source) { source.setEncoding('utf8') for await (const body of source) { console.log(`[${++counter}] - request!`, body) const item = JSON.parse(body) const result = sum(...Object.values(item)) yield `Result: ${result}` } }, res ) } catch (error) { console.log('Error!!', error) } }) .listen(PORT, () => console.log('server running at', PORT))
OK, ez szokatlan kódnak tűnhet egy egyszerű webes API esetében. Hadd magyarázzam el, mi történik.
Alternatív megoldásként ez az API a Node.js adatfolyamokon alapul . Tehát akkor olvassa el az on-demand adatok jövedelem kéréseket , feldolgozza, és reagáljon rájuk a választ objektumot.
On line (11)
there is a pipeline function that will manage the event flow. If something goes wrong in any stream function, it will throw an exception and we'll handle errors on the catch statement from try/catch.
On line (6)
we are importing the sum function from the Math module and then processing incoming data on line (19)
. Notice that on (19)
there is an Object.valuesfunction which will spread all object values and return them as an array. For example, an object {v1: 10, v2: 20}
will be parsed to [10, 20]
.
Running
If you have a Unix based system you can use the cURL
command, which is a native command to make Web requests. If you're working on the Windows Operating system, you can use Windows Subsystem for Linux or Git bash to execute Unix instructions.
Create a run.sh
file with the following code. You'll create code to request your API. If you're familiar with Postman you can skip this file and execute from there.
curl -i \ -X POST \ -d '{"valor1": "120", "valor2": "10"}' \ //localhost:3000
Note that youneed to install Node.js version 14
or higher.
You'll need to open two terminal sessions. On mine, I spliced two terminals in my VSCode instance. On the left run node server.js
and on the right run bash run.sh
as follows:

Debugging using Node.js Read-Eval-Print-Loop (REPL)
Node.js can help you create the best application possible. REPL is a mechanism for debugging and inspecting Node.js applications from the terminal. When you add the inspect
flag after the node
command, the program will stop right on the first code line as shown below:

First, you'll write the debugger
keyword right after the counter's console.log
on line (17)
and then execute node inspect server.js
again.
Note that you can interact with the REPL APIby using the commands listed in the official documentation.
In the next image, you'll see a practical example of how REPL works using some of the following commands:
list(100)
: shows the first 100 lines of codesetBreakpoint(17)
: sets a breakpoint on the 17th lineclearBreakpoint(17)
: removes a breakpoint on the 17th lineexec body
: evaluates thebody
variable and prints out its resultcont
: continues the program's execution
The image below shows in practice how it works:

I highly recommend that you try using the watch
statement. As in the browser, you can watch statements on demand. In your REPL session write watch(counter)
and then cont
.
To test the watch you need to choose a breakpoint – use setBreakpoint(line)
for it. As you run run.sh
, the program will stop on your breakpoint and show the watchers. You may see the following result on your console:

Debugging using Chromium-based browsers
Debugging in the browser is more common than debugging from terminal sessions. Instead of stopping the code on the first line, the program will continue its execution right before its initialization.
Run node --inspect server.js
and then go to the browser. Open the DevTools menu (pressing F12 opens the DevToolson most browsers). Then the Node.js icon will appear. Click on it. Then, in the Sources section you can select the file you want to debug as shown in the image below:

Debugging in VSCode
Going back and forth to the browser isn't really that fun as long as you write code in an editor. The best experience is to run and debug code in the same place.
But it's not magic. You configure and specify which is the main file. Let's configure it following the steps below:
- You'll need to open the
launch.json
file. You can open it by pressingCtrl
+Shift
+P
orCommand
+Shift
+P
on macOS, then writing launch. Choose the Debug: Open launch.json option. Additionally, you can press F5 and it might open the file as well. - In the next step of the wizard, click on the Node.js option.
- You may have seen a JSON file on the editor with the pre-configuration for debugging. Fill in the program field with your filename – this tells VSCode which is the main file. Notice that there is a
${workspaceFolder}
symbol. I wrote it to specify that the file is in the current folder I'm working on:
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": [ "/**" ], "program": "${workspaceFolder}/server.js" } ] }
Almost there! Go to the source code on server.js
and set a breakpoint on the 16th line by clicking on the left side of the code line indicator. Run it by pressing F5 and trigger the server.js using the run.sh, whichwill show the following output:

Debugging Docker-based applications
I personally love using Docker. It helps us stay as close as possible to the production environment while isolating dependencies in a receipt file.
If you want to use Docker you need to configure it in a Docker config file. Copy the code below, and create a new file beside the server.js
and paste it in.
FROM node:14-alpine ADD . . CMD node --inspect=0.0.0.0 server.js
First, you'll need to execute the Docker build command on your folder to build the app running docker build -t app .
. Second, you'll need to expose the debug port (9229) and the server port (3000) so either the browser or VSCode can watch it and attach a debugger statement.
docker run \ -p 3000:3000 \ -p 9229:9229 \ app
If you run the run.sh, file again, it should request the server which is running on Docker.
Debugging Docker apps on VSCode is not a tough task. You need to change the configuration to attach a debugger on a remote root. Replace your launch.json file with the code below:
{ "configurations": [ { "type": "node", "request": "attach", "name": "Docker: Attach to Node", "remoteRoot": "${workspaceFolder}", "localRoot": "${workspaceFolder}" } ] }
As long as your app is running on Docker and exposing the default debug port (9229) the configuration above will link the app to the current directory. Running F5 and triggering the app will have the same outcome as running locally.
Debugging remote code using VSCode
Remote debugging is exciting! You should keep in mind a few concepts before starting to code:
- What's is the IP Address of the target?
- How is the remote working directory set up?
I'll change my launch.json file and add the remote address. I have another PC at home which is connected to the same network. Its IP address is 192.168.15.12.
Also, I have the Windows Machine's working directory here: c://Users/Ana/Desktop/remote-vscode/.
The macOS is based on Unix systems so the folder structure is different than on my Windows machine. The directory structure mapping must change to /Users/Ana/Desktop/remote-vscode/.
{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "attach", "name": "Attach to Remote", "address": "192.168.15.12", "port": 9229, "localRoot": "${workspaceFolder}", "remoteRoot": "/Users/Ana/Desktop/remote-vscode/", "trace": true, "sourceMaps": true, "skipFiles": [ "/**" ] } ] }
In this particular case, you'll need at least two different machines to test it. I made a short video showing how it works in practice below:
Stop using console.log for debugging!
My tip for you today is about being lazy for manual stuff. Learn one new shortcut or tool per day to improve productivity. Learn more about the tools you've been working on every day and it will help you spend more time thinking than coding.
In this post, you saw how VSCode can be a helpful tool for debugging apps. And VSCode was just an example. Use whatever is most comfortable for you. If you follow these tips, the sky is the ?
Thank you for reading
Nagyon értékelem az együtt töltött időt. Remélem, hogy ez a tartalom nem csak szöveg lesz. Remélem, jobb gondolkodóvá és programozóvá is vált. Kövessen a Twitteren, és nézze meg a személyes blogomat, ahol minden értékes tartalmat megosztok.
Szia! ?