JavaScript is just a client-side programming language that runs in the browser, right? But this is no longer true. Node.js is a way to run JavaScript on the server; But it is more than that. If you are an interest in web development, then you should learn a bit about Node.js and why it is creating a wave in the community.
Why use Nodejs?
The first is the advantages of execution speed and scalability. Node.js is very fast. It is an important requirement when you are a startup trying to create a big product and want to ensure it can expand quickly, meet a large number of users as your website grows.
Node.js can handle thousands of concurrent connections. Besides the performance and scalability benefits, you probably already know a bit about JavaScript, so getting started is not too difficult. And the important thing is, Node.js is getting bigger and bigger.
Demo Nodejs to run the web server locally
Create an app.js file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; http.createServer((req, res) => { var body = 'Hello Worldn'; var content_length = body.lengthh; res.setHeader('Content-Type', 'text/plain'); res.writeHeader(200, { 'Content-Type' : 'text/plain', 'Content-Length' : content_length }); res.end(body); }).listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); }); |
writeHead () is called to write the response header to send to the client.
The end () method will send the response’s content to the clinet and notify the server that the response (header and content) has been sent.
Run the app.js file using the command line
Check
Nodejs Debugger
Suppose in the above code, instead of body.length , we mistakenly write body.lengthh. Content-length returned will be undefined.
In order to support error detection, we can use the nodejs debugger
node debug app.js
From version 6.3 onwards, nodejs uses the node inspect app.js
(debug nodes still run in larger versions).
When running the node inspect app.js
node will show the first 3 lines of the file
Continue to run the help command, we will see a list of commands that support debugging
For example, we run sb(9)
to set a breakpoint at line 9, cont
to continue
Return to the browser, reload and return to the terminal to see the code that will be executed to line 9
Running the repl command, typing the names of the variables, we see that the content_length variable is undefined, so we can judge that the line of code is happening.
Above is a simple piece of code and a brief introduction to the default debugger tool of nodejs that supports development.
Reference source: https://techmaster.vn/posts/33428/nodejs-la-gi-va-tai-sao-toi-nen-hoc-lap-trinh-nodejs