Showing posts with label node.js development. Show all posts
Showing posts with label node.js development. Show all posts

Friday, November 12, 2021

What’s New In Node.js 17?

What's New In Node.js 17

Latest version of Node.js has been officially released. Node.js is now officially available to users, contributors and app developers also. It supersedes Node.js 16 in terms of the current release line of this runtime and now it got promoted to LTS or long term support channel on 26th October. Rather than being a minor update, this release brings some refinements to the runtime, including more promisified APIs, Javascript engine upgrades and OpenSSL 3.0 support. Here we’ll discuss the latest release of Node.js 17 features. Let’s get started.

Also know the amazing Node.js security best practices at- Top 10 Node.js Security Best Practices

What’s New In Node.js 17?

1. New Promise-based APIs-

Node.js promisify its core APIs as a part of its strategic initiative plan. In Node.js 17, this ongoing promisification work is extended to the readline module, mainly used to accept input from command line. New APIs are accessible through readline/promises module. Old way of using readline module in Node.js v16 and earlier involved using callback functions as-

// main.mjs
import readline from "readline";
import process from "process";

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question(`What's your name?`, (name) => {
  console.log(`Hi ${name}!`);
  rl.close();
});

With Node.js 17, now you can use await when importing from readline/promises:

// main.mjs
import readline from "readline/promises";
import process from "process";

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const name = await rl.question(`What's your name?`);
console.log(`Hi ${name}!`);
rl.close();

2. Stack Traces-

Stack traces are important for node.js development companies and each common user of NodeJS runtime. It helps to detect errors affecting an app. Also it reveals the points that causes the errors. In this latest release , Node.js version will be present at the end of stack trace, especially when fatal exceptions force the process to exit. It’s helpful to have this capacity naturally because when somebody analyzes revealed errors, they’ll definitely need to discover the version of Node.JS they’re using. Node.js 17 has a command-line option that allows users and programmers to avoid extra information they don’t require. This line goes “–no-extra-info-on-fatal-exception.”

3. OpenSSL 3.0-

Now, node.js includes OpenSSL 3.0, particularly quictls/openssl, upgraded from OpenSSL 1.1.1.    OpenSSL 1.1.1 will reach the end of support on 2023-09-11, means before proposed End of life date for Node.js 18. Hence, it has been decided to include OpenSSL 3.0 in Node.js 17 to provide time for user testing and feedback before the next LTS release. Among all of the new features in OpenSSL 3.0 is the introduction of providers, of which FIPS provider that can be enabled in Node.js. OpenSSL 3.0 should be mostly compatible with those provided by OpenSSL 1.1.1, we can anticipate some ecosystem impact because of strict restrictions on the allowed algorithms and main issues.

In app with Node.js, if you hit ERR_OSSL_EVP_UNSUPPORTED error, it is somehow similar to that your app or module you’re using is using an algorithm or key size that is no longer allowed by default with OpenSSL 3.0. New command line option, –openssl-legacy-provider, has been included to revert to the legacy provider as a temporary workaround for strict restrictions..

For example-

$ ./node --openssl-legacy-provider  -p 'crypto.createHash("md4")'

Hash {
  _options: undefined,
  [Symbol(kHandle)]: Hash {},
  [Symbol(kState)]: { [Symbol(kFinalized)]: false }
}

4. V8 Is Upgraded To v9.5-

Node.js came with an updated V8 engine of Javascript to V8 9.5 in Node.JS 17. If you’re working with Node.js 16, programmers can rely on V8 9.4 meaning that latest one available on the previous version of runtime. Apart from performance-related tweaks and improvements, this new version brings some extra supported types for “Intl.DisplayNames” API and Extended options for “timeZoneName” in another API which is – “Intl.DateTimeFormat”.

5. Deprecations And Removals-

Node.js 17 comes with some removals and deprecations. Important one is deprecation of trailing slash pattern mappings that is not supported in the import maps specification.


Tuesday, June 8, 2021

Tips And Tricks To Make Your Node.js Web App Faster

 

Tips And Tricks To Make Your Node.js Web App Faster



Whenever we think about developing a web app, Javascript is the only language that comes to the mind. As per the stack report, Javascript is a popular programming language for web app development because it is easy to learn and works well when combined with other languages and can be used to build various apps. But with the latest trends, market competition increases and businesses are looking for the tools, technologies and  frameworks that allow them to hold a tight grip on various operating platforms with a single solution. Many organizations find Node.js a perfect solution for server-side development to meet the continuous need for apps that can run seamlessly and carefully on all platforms. But working on a Node.js project is not simple. If you may have experienced the issues regarding speed. Here we discuss some tips that are known to speed up your Node.js web application development tremendously. So, let’s see each of them one by one.

Know the amazing new features of Node.js 16 at- What’s New In Node.js 16?

Tips And Tricks To Make Your Node.js Web App Faster-

1. Limited Use Of Synchronous Functions-

Since Node.js is designed with single thread architectures and asynchronous coding is heavily used in Node.js to ensure non-blocking operational flow. With the availability of various synchronous components, it would block the applications and show down the app performance. Asynchronous coding lets you use queues to monitor workflow, allowing you to append extra tasks and add additional callbacks without blocking the main thread. While you are using the Asynchronous methods, in some cases, it is feasible to find your web page making some blocking calls. Don’t worry! This is common when you use third-party modules. So, you need to keep an eye on libraries and try to avoid them dominating synchronous calls.

2. Run In Parallel-

To deliver the HTML page for any dashboard, the node.js application needs to retrieve a lot of data for the dashboard. You need to make multiple internal API calls to fetch different data. When delivering the dashboard you may execute following hypothetical calls:

The user profile – getUserProfile().
The site list – getSiteList().
Subscriptions – getSubscriptions().
currnet site – getCurrentSite().
Notifications – getNotifications().

Basically, it needs to retrieve the data from user browsing session to verify they’re logged in and it needs to pull in data about the user and site for the dashboard. So as to retrieve this data, app needed to make some calls to internal API functions. Some of them could take up to 2 seconds to complete. Every request was made by a separate express middleware, means they were running in series. Each request would wait for previous one to complete before starting.

As node.js is well suited to run multiple asynchronous functions in parallel, and various internal API requests didn’t depend on each other, here come the parallelism- fire off all requests at once and then continue once all they’ve completed. 

You can do something like this:

function runInParallel() { 
async.parallel([
getUserProfile,
getSiteList,
getSubscription,
getCurrentSite,
getNotifications
], function(err, results) {
  //This callback runs when all functions complete });
}

3. Use Caching-

If you are fetching data that doesn’t change frequently, you may cache itto improve performance. For instance, following snippet fetched the latest posts to display on a view:

var router = express.Router();
router.route('/latestPosts').get(function(req, res) {
  Post.getLatest(function(err, posts) {
    if (err) {
      throw err;
    }
    res.render('posts', { posts: posts });
  });
});

If you don’t publish blog posts frequently, you can cache the posts array and clear the cache after interval. For instance, you can use redis module to do this. For that, you need to have Redis installed   on your server. Then you can use a client called node_redis to store key/value pairs. This snippet shows how we can cache the posts:

var redis = require('redis'),
    client = redis.createClient(null, null, { detect_buffers: true }),
    router = express.Router();
router.route('/latestPosts').get(function(req,res){
  client.get('posts', function (err, posts) {
    if (posts) {
      return res.render('posts', { posts: JSON.parse(posts) });
    }
    Post.getLatest(function(err, posts) {
      if (err) {
        throw err;
      }
      client.set('posts', JSON.stringify(posts));    
      res.render('posts', { posts: posts });
    });
  });
});

Thus, first of all we check if the posts exist in the Redis cache. If so, we deliver the posts array from cache. Otherwise, we retrieve the content from DB and then cache it. And after an interval we can clear the Redis cache so as to fetch the new cache.

4. Use GZip Compression-

Enabling the gzip compression can hugely impact the performance of web apps. When a gzip compatible browser requests for some resource, the server can compress the response before sending it to the browser. If you don’t use gzip for compressing static resources it may take more time to fetch for the browser. In Express app, you can use built-in express.static() middleware to provide the static content. Also, you can use middleware compression and provide the static content. Here, is a code snippet that shows how to do it:

var compression = require(‘compression’);
app.use(compression()); //use compression
app.use(express.static(path.join(_dirname, ‘public’)));

5. Make Use Of Client Side Rendering When Possible-

Because of the client-side MVC/MVVM frameworks like Ember, Meteor, and AngularJS eases the creation of single page applications. Rather than, rendering on the server side you will only expose APIs that send JSON responses to the client. On the client side, you can use a framework to consume the JSON and display on the UI. Sending JSON from server can save bandwidth and so improve speed because you don’t send layout markup with every request. Instead you just send simple JSON that is then rendered on the client side.

6. Use Standard V8 Functions-

Various operations on collections like reduce, map and forEach are not supported by all browsers. To solve the browser compatibility issues you can use some client side libraries on the front end. With Node.js you can use built-in functions for manipulating collections on server side.

7. Use nginx In Front Of Node-

Nginx is a lightweight server used to reduce load on your Node.js server. Rather than serving static files from Node, you can configure nginx to provide static content. You can also set up nginx to compress the response using gzip so that the response size is small. Hence if you’re running a production app you may need to use nginx to improve the speed. 

8. Minify And Concatenate JavaScript-

Your web app speed can be improved by minifying and concatenating various JS files into one. When the browser encounters a <script> element the page rendering is blocked until the script is fetched and executed. For instance, if a page includes six Javascript files, the browser will make six separate HTTP requests to fetch those. Performance can be improved to great extent by minifying and concatenating those six files into one. Similar applicable to CSS files also. You can use a build tool such as Gulp/Grunt to minify and concatenate asset files.

9. Optimize Queries-

Consider that you have a blogging app that shows the latest posts on the home page. You may write something like this to fetch data using Mongoose:

Post.find().limit(10).exec(function(err, posts) {
  //send posts to client
});

But, the issue is find() function in Mongoose fetches all fields of object and there might be some fields in the Post object that are not needed on the homepage. For example, comments field holds a comments array for a specific post. If you’re not showing the comments, you can exclude it while fetching. And this will improve the speed. We can optimize the above query with-

Post.find().limit(10).exclude('comments').exec(function(err, posts) {
  //send posts to client
});

10. Don’t Store Too Much In Sessions-

In an Express web app, the session data is stored in memory. When you store huge amounts of data in the session, it adds significant overhead to the server. Hence, you can switch to some other type of storage to keep session data or try to reduce the amount of data stored in session. For instance, when users log into an app, you can store their id in the session rather than storing the entire object. Consequently, on each request you can recover the object from the id. You may also need to use MongoDB or Redis to store session data.

Wrap Up-

Most of the web development companies and freelancers uses Node.js to build great web apps. Knowing the above tips and tricks will help you to improve the performance of Node.js web app. There can be some other tips too. If you are also thinking develop web app with Node.js, then you must know these tips. You can hire Node.js developers of Solace team for effective web app development. Connect with Solace and get a free quote for web app development. We will be happy to help you.


Friday, October 23, 2020

What’s New In Node.js 15?

 

Modern web applications are developed with many popular frameworks like Angular JS,  bootstrap and so on. These frameworks are based on popular Javascript frameworks. But when it comes to developing server-based applications, Node.js comes into the focus. It is also based on the JavaScript framework but used for developing server-based applications. In 2020, Node.js turned 11 years old, and the number of packages available on npm crossed one million. Downloads for Node.js itself continue to rise, growing 40% year over year. A lot has happened in a relatively short amount of time! Each year the Node.js community has gained momentum, and 2020 shows no signs of slowing down. There are lots of interesting features being explored for the next major releases of Node.js 15. Here we will see some major features in node.js 15.

New Features In Node.js 15-

1. N-API Version 7-

Node.js 15 eases the creation, build and support native modules.  It comes with N-API version 7 which includes some extra methods to work with array buffers-

napi_status napi_detach_arraybuffer(napi_env env, napi_value arraybuffer)
napi_status napi_is_detached_arraybuffer(napi_env env, napi_value arraybuffer, bool* result)

2. npm 7-

It is a major release that comes with new features including workspaces and a new package-lock.json formatNpm 7 also includes yarn.lock file support. There is a new change in the latest version with npm 7 – peer dependencies are installed by default. Npm team has worked to minimize potential disruption to existing projects because of the switch to automatically installing peer dependencies, if you face any problem, you can sue the –legacy-peer-deps flag at install time as a workaround to revert to the previous behavior. You can set it in the environment or npm config files.

3. AbortController-

The latest version of nodejs features an experimental implementation of AbortController. AbortController is a global utility class used to signal cancelation in selected Promise-based APIs, based on the AbortController Web aPI-

const ac = new AbortController();
ac.signal.addEventListener('abort', () => console.log('Aborted!'), { once: true });
ac.abort();
console.log(ac.signal.aborted);  // Prints True

Here, the abort event is emitted when ac.abort() is called. The AbortController will trigger the abort event once. Event listeners should use the { once: true } option (or EventEmitter API equivalent- once()) to check that the event listener is removed once the abort event is handled.

4. QUIC (experimental)-

It is a new UDP- based transport protocol which is underlying transport protocol for HTTP/3. QUIC features inbuilt security with TLS 1.3, flow control, error correction, multiplexing and connection migration. This latest version of node.js  comes with experimental support QUIC that can be allowed by compiling Node.js with –experimental -quic configuration flag. The Node.js QUIC implementation is exposed by the core net module:

const { createQuicSocket } = require(‘net’);

5. Updated handling of rejections-

Till the previous version of Node.js, if there was an unhandled rejection, you will get a warning regarding rejection and a deprecation warning.

For example, 

new Promise((resolve, reject) => {
  reject('error');
});

This would result in following deprecation message:

(node:31727) UnhandledPromiseRejectionWarning: error
(node:31727) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:31727) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

To avoid these warning messaging, handle rejection with a catch block: 

new Promise((resolve, reject) => {
  reject('error');
}).catch((error) => {});

As of Node.js 15, the default behavior has changed to:

node:internal/process/promises:218
          triggerUncaughtException(err, true /* fromPromise */); ^
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "error".] {
code: 'ERR_UNHANDLED_REJECTION'
}

This change is made to meet the community expectations and to help surface problems that would else be hard to detect an debug. It inlines the behavior of unhandled rejections with that for unhandled exceptions where throw behavior being useful. Node.js lets you to configure the default behavior for unhandled rejections through the –unhandled-rejections flag. If you want to revert to the previous default, just add the below command line: –unhandled-rejections=warn or through the 

NODE_OPTIONS evironment variable export 
NODE_OPTIONS=--unhandled-rejections=warn

Aso, you can handle rejection by adding an unhandledRejection listener:

process.on('unhandledRejection', (reason, promise) => {
  // do something
});

Know the- 6 Awesome Things You Can Do With NodeJS.

Monday, October 7, 2019

When, How And Why Use Node.js As Your Backend?

Backend is an important part of every software as it serves the functionality of a software product. Hence the selection of technology stack for this is also an important task. There are three fundamental things behind the decision of a technology stack for your software. 
  • Business priorities and objectives
  • Specifications of your business domain and market
  • Specifications of the technology stack itself.
Server side is the most significant part of your product. Among all conceivable back end development technologies to look over, Node.js is one of the essentials. It incorporates a wide variety of modern business domains and actual cases. The advantages of Node.js are uncountable, yet you ought to likewise know about its constraints. Get a full picture of Node.js and abstain from doing serious mistakes being developed that could cost you money.

What is Node.js?

Node.js is an application runtime environment that allows you to develop server-side applications in JavaScript. Its one of a kind I/O model exceeds expectations at the kind of scalable and real time situations we are progressively requesting of our servers. It is lightweight, efficient. Ability of Node to use JavaScript on frontend and backend opens new ways for development. This is the reason that many big companies are using Node. Here we will discuss about- When it is good to use Node and when not? 

How Node.js is different from web JavaScript?

There is no difference between web JavaScript and Node.js in terms of the language used. JavaScript used in browsers and in Node.js is actually the equivalent. Then what makes it special? Node has different set of APIs. In browsers, you have an variety of DOM/Web APIs uncovered that help you connect with UI and enable you to get to access the hardware. Node.js has many APIs that are suitable for backend development, for instance, support for file systems, http requests, streams, child processes etc. Browsers do offer some essential support for file systems or http requests, yet those are typically constrained because of security concerns. You can also know the JavaScript concepts that Node.js programmer must know at- 10 JavaScript concepts every Node.js programmer must master.

Why is it worth developing your project in Node.js?

As a matter of first importance, utilizing it as your server technology gives your team an extraordinary lift that originates from utilizing a similar language on both the front end and the back end. This, implies your team is increasingly productive and cross-functional, which, thusly, prompts lower development costs. Also it is good to mention that JavaScript is a popular programming language, so your applications code will be easy to understand for developers.
You can likewise reuse and share the code between the frontend and the backend parts of your application, which accelerates the development process. In addition, the community of Node.js is continuously increasing (StackOverflow questions are increasing), so the knowledge base for technology is widely available. The fact that the entire Node.js technology stack is open-source and free is additionally extraordinary news. Node offers a great package manager, npm and the amount of available open-source tools in npm’s registry is massive and rapidly growing. Here we will include some advantages of Node.js that you should consider when choosing a technology for a project.

Real time applications-

Choosing Node.js is good for those applications that need to process a high volume of short messages requiring low inertness. Such applications are called real time applications (RTAs). Node.js is used to create it effectively. Node.js will be the right choice for real-time collaborative apps, where you can watch the document being modified live by someone( for eg., Trello, Google Docs). You can develop video conference app, online gaming apps, e-commerce transaction software with Node.js. It can handle multiple client requests, enables sharing and reusing packages of library code and data sync between client and server can be very fast.

Fast and scalable environment-

Ruby on Rails probably won’t be sufficient regarding speed, if you have a huge amount of requests. Node.js will demonstrate valuable in circumstances when something quicker and more versatile than Rails is required. Node’s capacity to process numerous requests with low response times, just as sharing things, for example, validation code between the client and server, make it an extraordinary fit for modern web applications that carry out lots of handling on the client’s side. Hence Node.js is popular among single-page applications because there all rendering is done on the client’s side and the backend only provides a JSON API. Node.js also proves to be useful when you need to process high volumes of IO-bound requests. It won’t generally be all that proficient if a lot of CPU processing is required to serve the request. 

When you should not choose Node.js?

Applications with monolith architecture-

Monolithic apps contain lots of functionality. And Node.js is a single threaded platform. When something is being executed in a single thread, the rest of to pause. Server limits are utilized in a problematic manner, since one thread uses one processor core. Therefore large Node.js applications are created as sets of microservices or under a service-oriented architecture made of several services. Monolith applications of any complexity are acceptable if there is no high load involved.

Complex CPU calculations-

Node.js isn’t the best choice with regards to work with highly loaded threads that include CPU. For instance, when audio and video processing is written on the back end.

Package Quality-

There are more interesting points before commencing with Node.js. There are many packages available in npm for Node.js. The community of it is active and npm is the largest available repository these days. But packages vary in their quality. Some of the time, you can detect issues with packages supported just by individual clients and not kept up appropriately; for example, when associating your Node application to an old database framework.

How to use Node.js for your project?

When you choose a Node.js for your project development, go to the official web page of Node.js and download the Node.js package. After that, you need to install the Node.js package manager to install and manage the dependencies in project easily. Visit nmpjs.com and follow the installation instructions. Now you are ready to code.
The best beginning stage for the Node is the official guide, from which you can gain proficiency with the core concepts of Node.js. In it’s guide, you can find answers to most of the questions. Then you can try out some important frameworks such as express.js to get an overview of how JavaScript dependencies are used. It allows you to build high-performance, scalable and easily maintainable applications in JavaScript. The best learning method for express.js is to visit the official guides on the express.js web page. Now you will be ready to build applications.
Are you looking for a web development to boost your business? Then you are at the right place. We at Solace believe in benefits and effectiveness of using Node in development. Solace expert’s are well trained to use Node for effective development. To get a free quote for any web development, contact us. We are happy to help you get started through our expert’s.

Wednesday, August 28, 2019

Role of Node.js in Internet of things (IoT)


Internet Of Things-

So as to use innovation to initiate business development, one needs to watch out for technological expansion. In this way many organizations are advancing by identifying the next “big thing”.  
To overcome the problems and achieve smoother flow in a business, eventually, every business needs to use data management tools, network control, and intelligent solutions. It is difficult to recognize the perfect technology that best suits your business requirements. Extensively, IoT, big data analysis, the cloud will bring significant changes in business process management.
IoT(Internet of things) is all about synchronized and connected environments across the system. This includes the integration of microservices, web, wireless technology, sensors, and devices.
Here Node.js comes into the picture. For the IoT application development, most systems failed to provide a uniform experience across the devices and real-time reflection through embedded systems.

Rapid growth-

The popularity of Node.js is rapidly increasing, but no one expected it would grow this quickly. Node.js is built on Google’s V8 open source JavaScript engine. Node.js is known for its speed, scalability and efficiency. This makes it ideal for developing data-intensive, real-time applications. So Node.js best for the IoT, which is depend on data-intensive, real-time devices and applications. Effective and secure communications and interactivity are of fundamental significance in the IoT, which is the very reason why APIs lend themselves so well to the IoT model. The most widely accepted use case for Node.js is API- For example, the first thing LinkedIn built in Node.js was its mobile API.

What Makes the Node.js a Great Choice for IoT Applications?

Role of Node.js in Internet of things (IOT)

There are many frameworks such as Hapi, Express and Restify designed for creating APIs in Node.js. Even without a powerful pre-built solution, it takes only a few lines of code to get an API started using Node.js. Devices within the IoT, such as sensors, beacons and wearablesgenerate large number of requests. Node.js is perfect for managing these requests via streams that can be processed and monitored very efficiently. Stream instances are basically Unix pipes. They can be readable, writable or both, and are easy to work with. Streams allow users to pipe requests to each other, or stream data directly to its destination. No caching, no temporary data–just stream from one place to another.
It’s also essential to note that the Node.js community likes IoT technologies, and early adopters of IoT have a tendency to use Node.js for experiments and products. In fact, the Node Packaged Modules (NPM) repository is an indicator of the association between these communities. It consists of more than 80 packages for the Arduino controller. And over 15 for Bluetooth Low Power, and multiple packages for the Pebble and Fitbit wearable devices.
Node.js also has very low resource requirements. This is a feature that developers are already using in data-intensive IoT scenarios. From wearables to M2M, Node.js is best for IoT. The bottom line is that developers building data-intensive, real-time IoT applications says that Node.js is a best fit.
Indeed, with its proven performance and the simplicity with which an API code base can be maintained, Node.js fits the IoT use case very well.

Best practices to keep in mind when planning an API-first architecture for the IoT with Node.js:

  1. Build in fine-grained scalability and failover- By Writing multiple small API-First apps, you can independently scale out each functional component and gracefully fail-over when one instance goes down or crashes.
  2. Focus on producing a clean, extensible design- An API-based design makes state explicit so it can easily be passed from one component to another.
  3. Write lots of tiny apps- Instead of putting a big logic into a single process, separate functionality into smaller independent components that communicate with each other via APIs.
Need to develop iot for your business? Our expert’s are well trained for IoT development. They believe in the benefits of using Node.js for IoT development. To get a free quote for effective IoT development, contact us and will provide the means to bring your company the success it deserves.