Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that allows developers to build fast and scalable network applications by executing JavaScript code outside of a web browser.
To further enhance the performance and scalability of these applications, NCache—a high-performance, in-memory distributed cache—now offers support for Node.js. Essentially, it can utilize the NCache Client-Side API (basic operations, data expiration techniques, locking, etc.). Additionally, NCache’s support for Node.js-based Session Caching ensures that applications remain highly responsive and scalable, providing a seamless experience for users while maintaining optimal performance.
Why Use Node.js with NCache?
NCache’s enhanced caching capabilities provide numerous options for using Node.js seamlessly. For instance, if you want your Node.js application to run in a load-balanced environment with better performance, NCache offers the following advantages:
- Enhanced Performance: Data is stored in an in-memory cache closer to the application, yielding maximum performance and faster response time.
- Increased Reliability: If an application server goes down or data is lost, NCache provides reliability where the data remains available in such circumstances.
- Linear Scalability: NCache lets you add more cache servers when the transaction load grows for scalability. For example, while using your application, you can instantly add a new cache server depending on the situation and continue to serve more requests without stopping your application.
- High Availability and Fault Tolerance: While using NCache with the Node.js application in a web farm, NCache provides better fault tolerance by keeping the data available at all server nodes in a clustered cache with no single point of failure.
- Cache Topologies: NCache offers different caching topologies to make your application more reliable and scalable. For example, the Replicated Topology provides load balancing so your application does not suffer intensive traffic, and the Partition-Replica Topology provides higher reliability and scalability for faster transactions.
Client-Side Features of NCache
NCache has a variety of client-side features. Node.js can employ these features alongside their APIs and other methods. This blog discusses some of the features along with their implementation for a better understanding of caching data with Node.js.
Before using the below features, you need to install the npm package named ncache-client required for using the NCache client with Node.js. You can refer to the NCache Documentation to learn which versions of Node.js versions NCache supports. To do so, type the following command in the terminal section of Visual Studio Code. This package installs all the required client libraries for your Node.js application.
1 2 |
npm install ncache-client |
Next, to get started, include the following module in your application.
1 2 |
const ncache = require('ncache-client') |
Basic Operations for Caching Data
NCache provides various CRUD APIs for caching data using Node.js. The data can be a single item or a bulk and can be used synchronously to add, update, or remove from the cache. The implementation to add data in the cache with a custom object using add() is as follows.
1 2 3 4 5 6 7 8 |
// Get product from database against given product ID product = await this.fetchProductFromDB(1001); // Generate a unique cache key for this product and then create a CacheItem var key = "Product:" + product.getProductID(); var cacheItem = new ncache.CacheItem(product); // Add Product object to cache var version = await this.cache.add(key, cacheItem); |
Tag Cache Data
NCache provides Tags that allow you to associate keywords with your cache items for performing various operations on the data for efficient results. The implementation for adding data with tags using the setTags() property is provided below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Get customer from database against given customer ID var customer = this.fetchCustomerFromDB("ALFKI"); // Create a unique cache key for this customer. var key = "Customers:" + customer.getCustomerID(); // Specify tags var tags = new ncache.Tag[2]; tags[0] = new ncache.Tag("East Coast Customers"); tags[1] = new ncache.Tag("Important Customers"); // Create a new CacheItem var cacheItem = new ncache.CacheItem(customer); // Setting the tag property of the cacheItem cacheItem.setTags(tags); // Add customer object to cache var version = await this.cache.add(key, cacheItem); // CacheItem added successfully |
Data Expiration Strategies
NCache supports time-based data expiration strategies, i.e., Absolute Expiration and Sliding Expiration, where you specify the time interval to expire the cached data. The following is the implementation for adding/updating cache items with absolute expiration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Get product from database against given product ID var product = this.fetchProductFromDB(1001); // Generate a unique cache key for this product var key = "Product:" + product.getProductID(); // Create a new CacheItem for this product // You also need to specify the FQN (Fully Qualified Name) of the class var cacheItem = new ncache.CacheItem(product,"FQN.Product"); // Set Expiration type and TimeSpan var expiration = new ncache.Expiration(ncache.ExpirationType.Absolute, ncache.TimeSpan.FromMinutes(5)); cacheItem.setExpiration(expiration); // Add/Update item in cache with expiration await this.cache.insert(key, cacheItem); |
Session Caching with NCache
NCache provides a store for session data storage in Node.js, which uses express-session middleware to manage sessions. If your application runs in a web server farm and requires a reliable and scalable storage for your session persistence, then, NCache is the solution you need! Hence, I’ll discuss how to configure NCache for your Node.js sessions.
Step 1: Configure NCache in Config.json
First, NCache needs to be configured in the application’s config.json file by providing the cache name and other related properties as shown below.
1 2 3 4 5 6 7 8 9 |
{ "ncacheStore": { "ttl" : 3600, "cacheName" : "demoCache", "disableTouch" : false, "sessionTag" : "sess" } } |
To learn about the properties of Node.js Sessions, refer to the NCache Documentation.
Step 2: Configure NCache Store and Session Middleware in Express.js
Next, configurations must be done in the express.js file where session middleware is created along with NCache as a custom store to be used for data storage.
1 2 |
const store = await NCacheStore.CreateStore(config.ncacheStore); |
After configuring NCache as a data store, you are now ready to use Node.js sessions with NCache as your session persistence store. For a thorough understanding, refer to Session Caching Docs.
Step 3: Setting NCache as the Session Store
Session being made through the express-session middleware will use the NCache store as its custom store along with other properties shown below.
1 2 3 4 5 6 7 |
app.use(session{ secret: 'keyboard cat', resave: false, saveUninitialized: true, store: store }) |
Conclusion
NCache, as a distributed caching solution, seamlessly integrates with Node.js, allowing you to utilize its client-side APIs and methods, effortlessly. NCache enhances speed, improves performance, and provides both reliability along with scalability. Download NCache today!
Thanks for providing the information about Node.js in NCache that was very helpful for me. A lot of information can be useful for node.js developers. My Appreciation to you! Keep posting more content.
Your blog was absolutely fantastic! A great deal of great information and this can be useful some or maybe the other way. Keep updating your information.