node.js
I want to learn more about node.js.
References
Related
- V8 JavaScript Engine
- V8 is the name of the JavaScript engine that powers Google Chrome. It's the thing that takes our JavaScript and executes it while browsing with Chrome. V8 is the JavaScript engine (it parses and executes JavaScript code). The DOM and other Web Platform APIs are provided by the browser. The JavaScript engine is independent of the browser in which it's hosted.
- Other JS Engines:
- FireFox has SpiderMonkey
- Safari has JavaSciptCore
- V8 is written in C++, and it's continuously improved. It is portable and runs on Mac, Windows, Linux and several other systems. The implementation details of V8 can be found the V8 official site. V8 is constantly evolving to speed up the Web and the Node.js ecosystem.
- JavaScript is generally considered an interpreted language, but modern JavaScript engines no longer just interpret JavaScript, they compile it. JavaScript is internally compiled by V8 with just-in-time (JIT) compilation to speed up the execution. Compiling JavaScript makes perfect sense because while it might take a little bit more to have the JavaScript ready, once done it is going to be much more performant than interpreted code.
- Blocking
- In computing, a process that is blocked is waiting for some event, such as a resource becoming available or the completion of an IO operation. Once the event occurs for which the process is waiting, the process is advanced from blocked state to an intermittent one, such as runnable. In a multitasking computer system, individual tasks, or threads of execution, must share the resources of the system. Shared resources include: the CPU, network and network interfaces, memory and disk. When one task is using a resource, it is generally not possible or desirable for another task to access it., The techniques of mutual exclusion are used to prevent this concurrent use. When the other task is blocked, it is unable to execute util the final task has finished using the shared resource. Programming languages and scheduling algorithms are designed to minimize the over-all effect of blocking, A process that blocks may prevent local work-tasks from progressing. In this case
blocking
often is seen as not wanted. However, such work tasks may instead have been assigned to independent processes, where halting one has little to no effect on the other, since scheduling will continue. Deadlock means that processes pathologically wait for each other in a circle. As such it is not directly associated with blocking.
- In computing, a process that is blocked is waiting for some event, such as a resource becoming available or the completion of an IO operation. Once the event occurs for which the process is waiting, the process is advanced from blocked state to an intermittent one, such as runnable. In a multitasking computer system, individual tasks, or threads of execution, must share the resources of the system. Shared resources include: the CPU, network and network interfaces, memory and disk. When one task is using a resource, it is generally not possible or desirable for another task to access it., The techniques of mutual exclusion are used to prevent this concurrent use. When the other task is blocked, it is unable to execute util the final task has finished using the shared resource. Programming languages and scheduling algorithms are designed to minimize the over-all effect of blocking, A process that blocks may prevent local work-tasks from progressing. In this case
- Thread
- In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically part of the operating system. In many cases, a thread is a component of a process. The multiple threads of a given process may be executed concurrently (via multithreading capabilities), sharing resources such as memory, while different processes do not share these resources. In particular, the threads of a process share its executable code and thee values of its dynamically allocated variables and non-thread-local global variables at any given time.
- antipattern
- An anti-pattern is software engineering, project management, and business processes is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive. The term, coined in 1955, by computer programmer Andrew Koeing, was inspired by the book Design Patterns (which highlights a number of design patterns in software development that its authors considered to be highly reliable and effective).
- According to the authors of Design Patterns, there are two key elements to an anti-pattern that distinguish it from a bad habit, bad practice, or bad idea:
- The anti-pattern is a commonly-used process, structure or pattern of action that, despite initially appearing to be an appropriate and effective response to a problem, has more bad consequences than good ones.
- Another solution exists to the problem the anti-pattern is attempting to address. this solution is documented, repeatable, and proven to be effective where the anti-pattern is not.
Notes
Node.js is a free, open-source, cross-platform JavaScript runtime environment that lets developers create servers, web apps, command line tools and scripts.
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 runs a single process, without creating a new thread for each request. Node.js provides a set of asynchronous I/O primitives in its standard library that prevent JavaScript from blocking and generally, libraries in Node.js are written using non-blocking paradigms, making blocking behaviors 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 blocking 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 as a unique advantage because millions of frontend developers write JavaScript for the browser are now able to write server-side code in addition to the client-side code without the need to learn a completely different language. In Node.js, you are in charge of which ECMAScript version you use.
Node.js has a fantastic standard library, including first-class support for networking.
Example Application:
// createServer creates a new server and returns it
const { createServer } = require('node:http');
const hostname = '127.0.0.1';
// Server is set up to listen on a specified port and host name
const port = 3000;
// When a new request is received, the request event is called,
// providing two objects: a request and a response
const server = 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://${hostname}:${port}/`);
});
Installation
Node.js can be installed many ways, go to their website's install page to install Node.js for various operating systems. nvm
is a popular way to run Node.js. It allows you to easily switch the Node.js version, and install new versions to try and easily rollback if something breaks. It is also useful to test your code with old Node.js versions.
When node.js is installed, you have access to the node
executable in the command line.
Differences Between Node and the Browser
In the browser, most of the time what you are doing is interacting with the DOM, or other Web Platform APUs like Cookies. Those do not exist in Node.js. In Node.JS, you don't need to transpile your JavaScript to a different version of ECMAScript.
Difference between Deployment and Production
There is no difference between deployment and production in Node.js, i.e., there is no specific settings you need to apply to make Node.js work in a production configuration. However, a few libraries in the npm registry recognize using the NODE_ENV
environment variable and default it to development
setting. Always run your Node.js with the NODE_ENV=production
set.
In the popular express framework, setting the NODE_ENV
variable to production
generally ensures that:
- logging is kept to a minimum, essential level
- more caching levels take place to optimize performance
You can apply the environment variable by prepending it to your application initialization command:
$ NODE_ENV=production node app.js
Setting NODE_ENV
to anything but production
is considered an antipattern.
Node.js with WebAssembly
WebAssembly is a high-performance assembly-like language that can be compiled from various languages, including C/C++, Rust, and AssemblyScript. Currently, it is supported by Chrome, Firefox, Safari, Edge, and Node.js. The WebAssembly specification details two file formats, a binary format called a WebAssembly Module with a .wasm
extension and corresponding text representation called WebAssembly test format with a .wat
extension. You can use WebAssembly with Node.js. See this page for reference.
Do not run node in a production environment with the --inspect
option.
Profiling Node.js Applications
Profiling a Node.js application involves measuring its performance by analyzing the CPU, memory, and other runtime metrics while the application is running. This helps in identifying bottlenecks, high CPU usage, memory leaks, or slow function calls that may impact the application's efficiency, responsiveness and scalability. There are many third party tools available for profiling Node.js applications, but in many cases, the easiest option is to use the Node.js built-in profiler. The built-in profiler uses the profiler inside V8 which samples the stack at regular intervals during program execution. It records the results of these samples, along with important optimization events such as jit compiles, as a series of ticks:
code-creation,LazyCompile,0,0x2d5000a337a0,396,"bp native array.js:1153:16",0x289f644df68,~
code-creation,LazyCompile,0,0x2d5000a33940,716,"hasOwnProperty native v8natives.js:198:30",0x289f64438d0,~
code-creation,LazyCompile,0,0x2d5000a33c20,284,"ToName native runtime.js:549:16",0x289f643bb28,~
code-creation,Stub,2,0x2d5000a33d40,182,"DoubleToIStub"
code-creation,Stub,2,0x2d5000a33e00,507,"NumberToStringStub"
To run the app with the built in profiler, use the --prof
option:
$ NODE_ENV=production node --prof app.js
and put some load on the server using ab
(ApacheBench):
$ curl -X GET "http://localhost:8080/newUser?username=matt&password=password"
$ ab -k -c 20 -n 250 "http://localhost:8080/auth?username=matt&password=password"
Get an output of:
Concurrency Level: 20
Time taken for tests: 46.932 seconds
Complete requests: 250
Failed requests: 0
Keep-Alive requests: 250
Total transferred: 50250 bytes
HTML transferred: 500 bytes
Requests per second: 5.33 [#/sec] (mean)
Time per request: 3754.556 [ms] (mean)
Time per request: 187.728 [ms] (mean, across all concurrent requests)
Transfer rate: 1.05 [Kbytes/sec] received
...
Percentage of the requests served within a certain time (ms)
50% 3755
66% 3804
75% 3818
80% 3825
90% 3845
95% 3858
98% 3874
99% 3875
100% 4225 (longest request)
The output shows that we are only managing to serve 5 requests per second and that the average request takes just under 4 seconds round trip. Since the application was run with the --prof
option, a tick file was generated in the same directory as the local run of your application. Learn more about Node.js profiling here.
I will probably make a note going through the whole Node.js documentation, since there was some stuff that I learned by reading it so far. I don't have time to read all the documentation now though.
Comments
You can read more about how comments are sorted in this blog post.
User Comments
There are currently no comments for this article.