1566811419
Originally published at https://adrianmejia.com
There are multiple ways of handling concurrency on programming languages. Some languages use various threads, while others use the asynchronous model. We are going to explore the latter in detail and provide examples to distinguish between synchronous vs. asynchronous. Btw, What do you think your CPU does most of the time?
Is it working? Nope; It’s idle!
Your computer’s processor waits for a network request to come out. It idles for the hard drive to spin out the requested data, and it pauses for external events (I/O).
Take a look at the following graph to see the average time this system event takes (in nanoseconds)
As you can see in the chart above, one CPU can execute an instruction every one ns (approx.). However, if are in NYC and you make a request to a website in San Francisco, the CPU will “waste” 157 million cycles waiting for it to come back!
But not everything is lost! You can use that time to perform other tasks if you use a non-blocking (asynchronous) code in your programs! That’s exactly what are you going to learn on this post.
NOTE: Most programs on your operating system are non-blocking so a single CPU can perform many tasks while it waits for others to complete. Also, modern processors have multiple cores to increase the parallelism.
Let’s see how we can develop non-blocking code that squeezes out the performance to the maximum. Synchronous code is also called “blocking” because it halts the program until all the resources are available. However, asynchronous code is also known as “non-blocking” because the program continues executing and doesn’t wait for external resources (I/O) to be available.
In computing, input/output orI/O
(orio
orIO
) is the communication between a program and the outside world (file system, databases, network requests, and so on).
We are going to compare two different ways of reading files using a blocking I/O model and then using a non-blocking I/O model.
First, consider the following blocking code.
Synchronous code for reading from a file in Node.js
const fs = require('fs');console.log(‘start’);
const data = fs.readFileSync(‘./file.txt’, ‘utf-8’); // blocks here until file is read
console.log('data: ', data.trim());console.log(‘end’);
What’s the output of this program?
We are using Node’s readFileSync
.
Sync
= Synchronous = Blocking I/O model
Async
= Asynchronous = Non-blocking I/O model
That means that the program is going to wait around 23M CPU cycles for your HDD to come back with the content of the file.txt
, which is the original message Hello World!
.
The output would be:
start
data: Hello World!
end
How can make this code non-blocking?
I’m glad you asked. Luckily most Node.js functions are non-blocking (asynchronous) by default.
Actually, Ryan Dahl created Node because he was not happy with the limitations of the Apache HTTP server. Apache creates a thread for each connection which consumes more resources. On the other hand, Node.js combines JavaScript engine, an event loop, and an I/O layer to handle multiple requests efficiently.
As you can see, asynchronous functions can handle more operations while it waits for IO resources to be ready.
Let’s see an example of reading from a file using the asynchronous code.
Asynchronous code for reading from a file in Node.js
We can read from the file without blocking the rest of the code like this:
const fs = require(‘fs’);console.log(‘start’);
fs.readFile(‘./file.txt’, ‘utf-8’, (err, data) => {
if (err) throw err;
console.log('file.txt data: ', data.trim());
});console.log(‘end’);
What’s the output of this program?
See the answer
Many people get surprised by the fact that start
and end
comes before the data
output. 👀
The end
comes before the file output because the program doesn’t halt and continue executing whatever is next.
That’s cool, but does it make a lot of difference? It does, let’s bigger files and time it!
Blocking vs. Non-Blocking I/O model Benchmark
For this benchmark, let’s read a big file. I just went to my downloads and took the heaviest. (You can try this experiment at home and comment your results)
const fs = require(‘fs’);console.time(‘readFileSync’);
for (let x = 0; x < 10; x++) {
const largeFile = fs.readFileSync(‘/users/admejiar/Downloads/Docker.dmg’);
console.log(File size#${x}: ${Math.round(largeFile.length / 1e6)} MB
);
}const data = fs.readFileSync(‘./file.txt’, ‘utf-8’); // blocks here until file is read
console.log('file.txt data: ', data.trim());console.timeEnd(‘readFileSync’);
Notice that we are using console.time
which is very nice for benchmarking since it calculates how many milliseconds it took. The output is the following:
File size#0: 523 MB
File size#1: 523 MB
File size#2: 523 MB
File size#3: 523 MB
File size#4: 523 MB
File size#5: 523 MB
File size#6: 523 MB
File size#7: 523 MB
File size#8: 523 MB
File size#9: 523 MB
file.txt data: Hello World!
readFileSync: 2572.060ms
It took 2.5 seconds to read all ten files and the file.txt
.
Let’s try now the same with non-blocking:
const fs = require(‘fs’);console.time(‘readFile’);
for (let x = 0; x < 10; x++) {
fs.readFile(‘/users/admejiar/Downloads/Docker.dmg’, (err, data) => {
if (err) throw err;
console.log(File size#${x}: ${Math.round(data.length / 1e6)} MB
);
});
}fs.readFile(‘./file.txt’, ‘utf-8’, (err, data) => {
if (err) throw err;
console.log('file.txt data: ', data.trim());
});console.timeEnd(‘readFile’);
And here is the output:
readFile: 0.731ms
file.txt data: Hello World!
File size#7: 523 MB
File size#9: 523 MB
File size#4: 523 MB
File size#2: 523 MB
File size#6: 523 MB
File size#5: 523 MB
File size#1: 523 MB
File size#8: 523 MB
File size#0: 523 MB
File size#3: 523 MB
Wow! Totally random!
It got to the console.timeEnd
in less than a millisecond! The small file.txt
came later, and then the large files all in a different order. As you can see non-blocking waits for nobody. Whoever is ready will come out first. Even though it is not deterministic, it has many advantages.
Benchmarking asynchronous code is not as straight forward since we have to wait for all the operations to finish (which console.timeEnd
is not doing). We are going to provide a better benchmark when we cover Promise
s.
Take a look at this picture:
That async programs will take as long the most time-consuming task. It executes tasks in parallel while the blocking model does it in sequence.
Non-blocking code is much more performant. Blocking code waste around 90% of CPU cycles waiting for the network or disk to get the data. Using non-blocking code is a more straightforward way to have concurrency without having to deal with multiple execution threads.
For instance, let’s say you have an API server. In the image below, you can see how much more requests you can handle using non-blocking vs. using the blocking code.
As you saw earlier, the blocking API server, attend one request at a time. It serves the request #1, and it idles for the database and then is free to serve the other requests. However, the non-blocking API can take multiple requests while it waits for the database to come back.
Now that you are (hopefully) convinced why writing non-blocking code is necessary, let’s see different ways we can manage it. So far, we used callbacks, but there are other ways to handle it.
In JavaScript, we can handle asynchronous code using:
I’m going to cover each one in a separate post. Stay tuned!
Thanks for reading ❤
If you liked this post, please do share/like it with all of your programming buddies!
Follow us on Facebook | Twitter
☞ The Complete JavaScript Course 2019: Build Real Projects!
☞ Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
☞ JavaScript Bootcamp - Build Real World Applications
☞ JavaScript Programming Tutorial - Full JavaScript Course for Beginners
☞ New ES2019 Features Every JavaScript Developer Should Know
☞ Best JavaScript Frameworks, Libraries and Tools to Use in 2019
☞ JavaScript Basics Before You Learn React
☞ Build a CMS with Laravel and Vue
☞ The Complete Node.js Developer Course (3rd Edition)
☞ Angular & NodeJS - The MEAN Stack Guide
☞ NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)
☞ Best 50 Nodejs interview questions from Beginners to Advanced in 2019
☞ Node.js 12: The future of server-side JavaScript
☞ An Introduction to Node.js Design Patterns
☞ Basic Server Side Rendering with Vue.js and Express
#node-js #javascript #web-development
1619588820
The Js at the end of both Node and React refer to the language of JavaScript. Node and React are both the frameworks of JavaScript. However, the ensuing language that both the frameworks have been the same, the use cases for both of these frameworks. However, they are totally different.
Some people might even argue that to find the difference between node js and react js is just like comparing a train to an airplane. Both of them work on an entirely different domain. The main reason why Node and React’s comparison is unfair is that Node.js is a framework to handle back-end, meaning it is developed to handle the server-side computations.
Meanwhile, React.js was developed to handle the User Interface and User Experience (UI/UX). Although glaringly present, the differences do not take anything away from the sheer power and the versatility that each of these frameworks brings into their respective domain. Another way to string together the main difference would be that neither Node.js or React.js are interchangeable at any stage of your web development project.
With that being said, there are individual minute differences that any developer should consider when working on their projects, such as the performance, the learning curve, the community of both the frameworks and microservices’ support. Listed below, you will find a comprehensive weighted comparison of node js vs. react js on the aforementioned grounds. But before we begin our comparison, we must first understand both Node.js and React.js intricately and discuss the various use cases of these technologies.
Read: Difference between NodeJS and Django
The need for a robust means to handle the backend, server-side development yielded the framework we know as Node.js. Node.js was developed by Google and is based out of their V8 engine present in their web browser, i.e., Google Chrome. Node.js is a lightweight framework mainly because of its event-driven nature and the fact that it does not block the I/O. Node.js really shines the brightest when used to host API’s, access the database for the website, and serve the HyperText Transfer Protocol.
Node.js enjoys a very diverse clientele, with major players like Netflix, Uber, and Trello, all making use of Node.js in their backend. The reason why each of these companies uses this framework is different. Netflix, the leading online content streaming service, has to conduct A/B testing; only then would they serve the 93 million active users of their streaming service. The lightweight nature of Node.js has allowed them to serve the content swiftly. They have both reduced their startup time by over 70% and improved their scalability by shifting to Node.js.
#node js #node js vs react js #react js
1621320738
Whether MNCs or Startups, many companies use Angular.JS or Node.JS to develop web applications as these are among the best JavaScript frameworks used for web applications.
According to Statista, Node.JS and Angular.JS are the best frameworks used by developers, with 51.4% and 25.1%, respectively.
Both these frameworks have unique features and advantages, which makes them preferred over the other frameworks.
Many enterprises use these frameworks without even understanding their uniqueness and the type of projects they are suited or made, which is why, today, I will compare some of the best features and advantages of these two frameworks.
So, let’s dive into and learn various things about Angular.JS vs Node.JS without any further delay.
Angular.JS
AngularJS is a fundamental framework for robust web apps. It makes you use HTML as your template language and allows you to spread HTML’s syntax to clearly and succinctly express your application’s components.
AngularJS’s dependency injection & data binding eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it a perfect partner with any server technology.
AngularJS is what HTML would have been having it been designed for applications. HTML is a great declarative language for static documents. It does not contain much in creating applications.
Let’s discuss some main features of Angular.JS and its advantages:
Data Binding
Data binding is probably the most impressive and helpful feature of AngularJS. It will save you from writing a considerable amount of repetitive code.
A typical web application can contain up to 80% of its codebase, dedicated to traversing, manipulating, and listening to the DOM. Data binding makes this code escape so you can concentrate more on your application. Think of your Model as the only source of truth for your application. Your model is where you go to read or update anything in your application.
Data binding directives provide a projection of your Model to the application’s view. This projection is perfect and occurs without any effort on your part.
HTML UI
Another great feature of AngularJS is the fact that it uses the HTML language to build UI. The HTML language is a general and declarative language with concise tags that are easy to understand.
This leads to a more systematic and straightforward UI. JavaScript interfaces are usually more challenging to organize and develop. If you’re looking for a solution that’s fast, easy, and simple to use at a moment’s notice, then this could be it.
Model View Controller (MVC)
MVC is a software design pattern for developing web applications. It is made up of:
Directives allow angular to provide additional functionality with the HTML language. Directives can also be used to “decorate” components with behavior and manipulate DOM attributes in interesting ways. The controller does not need to control the DOM directly, as this must be done through directives.
Directives are a separate part of the set of elements that can be used anywhere other than a web application. The directives provide developers with the element-rich HTML they need to strengthen their online presence.
If you are looking to hire a dedicated angular developer, you can hire an angular js development company.
Node.js is a free and open-source server environment that runs on various platforms(Windows, Linux, Unix, Mac, OS X, etc.). Node.js uses JavaScript on the server.
Node.js is preferred because of its rich library of several JavaScript modules that helps in simplifying web development to a greater extent. Many companies hire Node.js developers for making a NodeJS web application development as it possesses many features.
Read More - https://www.valuecoders.com/blog/technology-and-apps/angular-js-vs-node-js-find-the-best-for-your-project/
#hire nodejs developer #node js development services #hire node js developer #hiring node js developers #hire node js developers #hire dedicated angular js developer
1616671994
If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.
If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.
WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.
So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech
For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers
1598839687
If you are undertaking a mobile app development for your start-up or enterprise, you are likely wondering whether to use React Native. As a popular development framework, React Native helps you to develop near-native mobile apps. However, you are probably also wondering how close you can get to a native app by using React Native. How native is React Native?
In the article, we discuss the similarities between native mobile development and development using React Native. We also touch upon where they differ and how to bridge the gaps. Read on.
Let’s briefly set the context first. We will briefly touch upon what React Native is and how it differs from earlier hybrid frameworks.
React Native is a popular JavaScript framework that Facebook has created. You can use this open-source framework to code natively rendering Android and iOS mobile apps. You can use it to develop web apps too.
Facebook has developed React Native based on React, its JavaScript library. The first release of React Native came in March 2015. At the time of writing this article, the latest stable release of React Native is 0.62.0, and it was released in March 2020.
Although relatively new, React Native has acquired a high degree of popularity. The “Stack Overflow Developer Survey 2019” report identifies it as the 8th most loved framework. Facebook, Walmart, and Bloomberg are some of the top companies that use React Native.
The popularity of React Native comes from its advantages. Some of its advantages are as follows:
Are you wondering whether React Native is just another of those hybrid frameworks like Ionic or Cordova? It’s not! React Native is fundamentally different from these earlier hybrid frameworks.
React Native is very close to native. Consider the following aspects as described on the React Native website:
Due to these factors, React Native offers many more advantages compared to those earlier hybrid frameworks. We now review them.
#android app #frontend #ios app #mobile app development #benefits of react native #is react native good for mobile app development #native vs #pros and cons of react native #react mobile development #react native development #react native experience #react native framework #react native ios vs android #react native pros and cons #react native vs android #react native vs native #react native vs native performance #react vs native #why react native #why use react native
1622719015
Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices.
Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend.
Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently.
The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.
Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers.
The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module.
Alongside prevalence, Node.js additionally acquired the fundamental JS benefits:
In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development).
This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable.
In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based.
There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations).
Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.
Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while.
Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements.
Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility.
Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root.
What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations.
Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation.
In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.
So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development.
I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call.
Good Luck!
#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development