Skip to content

Category: Node.js

Node.js – Beginner to Pro (Basic Ideas of Node.js)

What is Node.js?

Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js is not a programming language. It is only a runtime for JavaScript. Previously, JavaScript only worked in client side. But by using Node.js, JavaScript also can handle server side requests now.

What is Chromes V8 JavaScript Engine?

V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++. It is used in Chrome and in Node.js, among others. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linux systems that use x64, IA-32, ARM, or MIPS processors. V8 can run standalone, or can be embedded into any C++ application.

How Node.js works in server side?

Node.js pass the JavaScript code to V8 engine and V8 engine process the code and send the result to Node.js. Node.js and V8 JavaScript Engine are both are written in C++. So V8 Engine can directly interact with machine and the operating system. Google Chrome also use V8 engine to render JavaScript code.

How Node.js uses non-blocking I/O?

Non-blocking I/O defines, when a browser or client sends the JavaScript code to V8 engine, the browser won’t block any I/O operation by waiting for the response.

Here is an example of Blocking I/O.

const getUserSync = require('./src/getUserSync')

const userOne = getUserSync(1)
console.log(userOne)

const userTwo = getUserSync(2)
console.log(userTwo)

const sum = 1 + 33
console.log(sum)

For the above code, it will first fetch the first user. So second user will wait for fetching the first user. After fetching first user, it will fetch the second user. At last it will calculate the sum.

Here is an example of Non-Blocking I/O.

const getUserSync = require('./src/getUserSync')

getUser(1, (user) => {
    console.log(user)
})

getUser(2, (user) => {
    console.log(user)
})

const sum = 1 + 33
console.log(sum)

For the above code, calculating sum will not wait for any of the user fetching. So if the data fetching is getting late, it will print the sum first and after that it will print the user data in a order they are fetched.

That’s all for today. I hope you will enjoy this series. If you have any question please do not hesitate to write in comment.

References

https://nodejs.org/en/

https://v8.dev/

2 Comments