JavaScript (JS) is an object-oriented programming language that allows engineers to produce and implement complex features within web browsers. JavaScript is popular because of its versatility and is preferred as the primary choice unless a specific function is needed. In this Zone, we provide resources that cover popular JS frameworks, server applications, supported data types, and other useful topics for a front-end engineer.
Today, I came back writing a short but helpful tutorial on how to create an animated JavaScript radar chart. This chart is also known as a web or spider chart. We will create the chart using TypeScript, NodeJS, and LightningChart JS library (lcjs). What Is a Radar Chart? This is a graphical method of displaying multivariate data as a two-dimensional chart with three or more quantitative variables presented on axes. Data lengths of spokes are proportional to the magnitude of the variable for each data point versus the maximum magnitude for the variable across all data points. Generally, radar charts assist in decision-making by guiding us to the most trending properties. However, within a radar chart, we can have many properties that together form an observation object. On a single chart, multiple polygons can be displayed by plotting multiple observations—for example, the abilities of an athlete: speed, strength, agility, etc. The property with the lower tendency or value will help us to consider which athlete's ability should be improved in order to have a more balanced spectrum. Animation in a Radar Chart If you're looking for an exciting way to visualize data, you can't go wrong with additional JavaScript animation for the radar chart. Radar charts are created by plotting multiple data points on a two-dimensional grid. The grid is then overlaid with a web of lines, with each line representing a different data point. This makes it easy to see how the different data sets relate to each other. When you add animation to the mix, you can really bring your data to life. For example, animated radar charts can be used to show changes over time or to compare different data sets side by side. These charts are also great for showing relationships between different variables. So if you're looking for an engaging way to visualize data, an animated radar chart is definitely worth considering. Lets' now begin with our project. Setting Up Our Template 1. To follow the tutorial, please download the .ZIP project from LightningChart's website. 2. Once you have opened the project in Visual Studio, you will see a file tree like this: 3. Now, open up a new terminal 4. Run the npm install command, which is necessary for all NodeJS projects. This concludes our initial setup. Let's code. CHART.ts Our chart, animations, and data formatting logic will be contained in this file. 1. Initially, we will have to declare the constant lcjs that will refer to our @arction/lcjs library, where we will pull the charts library from. JavaScript // Import LightningChartJS const lcjs = require('@arction/lcjs') 2. Now you will need to extract the following (required) classes from the lcjs library: JavaScript const { lightningChart, SpiderWebMode, Themes } = lcjs 3. Now, we create the CHART object. JavaScript const chart = lightningChart().Spider({ theme: Themes.darkGold, }) .setTitle('Animated Radar Chart') .setAxisInterval(100) // Configure spider to be circular (like a traditional Radar Chart). .setWebMode(SpiderWebMode.Circle) Parameters: setTitle: defines the text label that will display as the title of the chart. setAxisInterval: defines the interval between each of the axes within the chart. Theme: by default, a collection of color themes can be accessed within the library. Notice that the color themes must be declared when the chart is created and cannot be changed afterward, as this would destroy the visualization and will require rebuilding the component. setWebMode: it sets the mode of the SpiderCharts web and its background. JavaScript const series = chart.addSeries() 4. Create the LineSeries object. This is a method for adding a new LineSeries to the chart. This series type visualizes a list of Points (pair of X and Y coordinates) with a continuous stroke. Notice: the LineSeries component is optimized for handling massive amounts of data. A static dataset in the tens of millions range is rendered in a matter of seconds. When streaming data, even millions of data points can be streamed every second while retaining an interactive document. For instance, when measuring three different line series performances on a high-end device (Ryzen 9 5900X, 64 GB, RTX 3080): Static line charts are capable to render more than 500 million data points. A threshold of 100 million data points loads up in 6.5 seconds. Refreshing line charts can handle more than two million data points at a refresh date of 10 Hz, overall using only 31% of CPU resources. Appending line charts may present up to 20 different live-streaming data channels. Totaling more than four million data points processed in real time. The FPS rate is 128 at an average CPU usage of 50%. 5. Adding properties to the series. JavaScript const categories = ['Category A', 'Category B', 'Category C', 'Category D', 'Category E'] series.addPoints( { axis: categories[0], value: 100 }, { axis: categories[1], value: 100 }, { axis: categories[2], value: 100 }, { axis: categories[3], value: 100 }, { axis: categories[4], value: 100 } ) Here is where you enter the data. Each series will need the axis name and its value. You can store all these values in an array and just map all the members. 6. Updating values randomly. Here is where we create the animated effect. To build the animated web effect, we need to update the values of each value. For instance, you can create a function that loads a JSON file with the source data and map that file. In this case, we have a function that creates random numbers for each of the categories. To update the default value of each category, we need to use the function [addPoints]. Setup randomization of series values at regular intervals: JavaScript const randomizePoints = () => { for (const category of categories) { const value = Math.random() * 100 series.addPoints({ axis: category, value }) } } In this example, the [randomizePoints] function will be executed every two seconds by the [setInterval] function. With the [setInterval] function, we are defining the axis scale interval. The first value will correspond to the series, and the second to the refresh time measured in milliseconds. Running the Application As usual, we will have to run the npm start command, which will provide the local host URL. Follow the link and open the final application in your browser. Here is the final JS animated radar chart application.: Need further help? In case you need assistance with your code, send me a message. I'll be happy to help.
JavaScript has emerged as the prominent scripting language among the next cohort of developers. It is an incredible tool for front-end programming, building interactive, feature-loaded websites, and fast and smooth web applications. Every front-end programmer knows JavaScript, however, when used without knowledge, it can make things worse. Poor JavaScript code can impact the website's performance, rendering speed, and load time. In this blog post, we will share some tips to help you optimize your JavaScript journey for the future. Let’s have a look: 1. Minify JavaScript code for small file — Minifying code is not similar to obfuscating code. However, both are ways of converting JavaScript — to be more complex to read or to make it smaller. Minifying accomplishes the latter and can shrink file sizes to reduce page load times. Line breaks, extra spaces, comments, etc., all increase the size of a JavaScript file and affects the pace at which the page loads. Minifying the code solves this problem. 2. Exclude unused components of .js libraries — The developers make use of JavaScript libraries such as jQuery UI or jQuery Mobile and others as is. It means the code comprises all the components of each library when you may need a few. If you are proficient in understanding what components will be incorporated in which package of a library, go for those particular ones. Your website will load more rapidly and guests will get a great experience. 3. Use HTTP/2 protocol — This updated version of the main Internet protocol i.e., HTTP, can offer a lot of cool features to developers. One of its numerous merits is multiplexing. This lets you use a TCP connection to take analogous requests and replies concurrently. Moreover, the earlier internet protocol requires a thorough understanding and enhanced knowledge of JavaScript theory, and HTTP/2 can make JavaScript load quickly. Therefore, HTTP/2 is much better than the HTTP protocol in terms of performance. 4. GZIP module for Apache, Node.js, and Nginx — GZIP is an amazing compression technology introduced years back when the Internet wasn’t as high-pace as it is currently. It reduces files on web servers, compressing static files down to about 80 to 90% of their true size. As JavaScript is a textual file, you can use GZIP to minify JavaScript files and also help to decline page load times. There are modules available for web servers including Nginx, and Apache. Since JavaScript is used for both front-end programming and back-end programming, JS files can be compressed with the zlib module for Node.js. // Code to run zlib module Const zlib = require(‘zlib’); Code to use GZIP: Const gzip = zlib.createGzip(); Const fs = require(‘fs’); Const inp = fs.createReadStream(‘input.txt’); Const out = fs.createWriteStream(‘input.txt.gz’); Inp.pipe(gzip).pipe(out); 5. Shorten DOM and access size — DOM (Document Object Model) is a data representation of the objects that make the structure of a web page. Every web page is documents usually an HTML file, and each object within a document is known as a node. JavaScript influences the DOM and its nodes to alter the structure, style, and content as a reply to user input. Every time JavaScript code accesses a DOM component or modifies DOM, depending on what a developer is doing. This takes more memory and slows down performance if a system has to recalculate several nodes within a DOM. Pruning lengthy DOM trees is a good notion to implement when optimizing the code. There are many advantages of keeping the DOM smaller: Less risk of memory leakage Optimize network efficacy and load performance Good performance at execution Here are a few methods to minimize the DOM: Reduce DOM references Evade complicated animations Keep simple norms of CSS 6. Keep JavaScript Code and CSS in the head section — This method helps your web page load faster; however, you need to have good knowledge of DOM and SCCOM. The idea is to keep less CSS and JavaScript code in the head section, so the page loads immediately, while the more general code is kept in distinct .css and .js files as usual. 7. Forget await and go for Promise.all — Rather than waiting for execution, you should roll up the calls and unsolved promises into an array. For instance, if you want to make more than one call to the database, you will usually wait for each time-consuming call. //Code to call two databases const getUsers = async () => { const consumers = await findAllConsumers(); const managers = await findAllManagers(); Return { consumers, managers} } One of the best ways is to run both calls together and resolve the outputs around half of the time. // code to call both databases simultaneously const getUsers = async () => { const consumers = findAllConsumers(); const managers = findAllManagers(); Return Promise.all([consumers, managers]); } You did not have to wait for the execution of two databases distinctly; however, both run in parallel. 8. Code busting — It is the practice of breaking the code across functional elements within small files that can be called when needed. Splitting code into small chunks replaces the load time of a single large JavaScript file with fractional load times for particular functions and features of your app. You can use different available bundlers to split code for application optimization. 9. Test your code — Testing is crucial to identify performance issues like memory leaks and recovering them. Here are some common JavaScript testing tools: Console.time() — It is a built-in JavaScript function that you can utilize to check how long a procedure takes. At the beginning of the process, just call: Console.time(label); Here, the label can be a unique name you give to the timer. At the end of the process, just calls: Console.timeEnd(label); Writing this code provides you with an effective process time. YSlow — It is an open-source performance measuring tool that evaluates websites and gives performance improvement tips. YSlow calls your site and compares its performance against Yahoo’s standards for website performance. It will endow you with a score between 0 and 100 percent. This is a great way to enhance your code for better performance. 10. Run the application in a cluster — In Node.js, you can utilize the cluster module to run a child process that will run concurrently with the parent process. The child clusters or processes run in its V8, event loop, and memory. This will distribute the load and tasks for every process. 11. Memory overflow — It is a state where a process finishes using memory but does not return it to the causal Operating System to be utilized by another application or process. Every time you create an object or declare a variable in JavaScript, memory is occupied. Memory overflow occurs when you are done with an object or variable, but the JS runtime still deliberates you require it. This impact the system performance as resources that should be freed up for other processes that are no longer available. The best way to evade JavaScript memory leaks is to manage your scope appropriately. 12. Asynchronous loading: Defer, and Async tags — Asynchronous loading of JavaScript means that the site loads in a multi-streamed way. When the web browsers find the string with <script src =”some.js”></script>, it will halt creating DOM and CSSOM models while the JavaScript is executed. This is the reason most JavaScript code is placed after the main HTML code. Take a look at the following code to comprehend this: <html> <head> </head> <body> This will not appear until hello.js is loaded. </body> </html> You can add an async tag to the JavaScript so that the DOM model is created in parallel and won’t be disturbed when the JavaScript is loading and executed. Wrapping Up So, we tried to provide you with the top 12 tips to improve your JavaScript journey. You may find it difficult to remember all the above-said tips in one go. But with practice, you will learn all these methods and witness a momentous improvement in your JavaScript performance. If you want to improve your website page's loading speed with any of the above optimization methods, contact AngularJS programmers to get the work done. Hope you find this blog helpful.
Even when you pass an object to a function or method, you are passing this object by reference, not the value. If you pass (or copy) an object by reference and then change any property, the ‘source’ object’s property also changes. In any example, I’ll use the object below JavaScript const sourceObject = { l1_1: { l2_1: 123, l2_2: [1, 2, 3, 4], l2_3: { l3_1: 'l3_3', l3_3: () => 'l3_3' } }, l1_2: 'My original object' } ‘Standard’ Cloning We’ll use a ‘standard’ cloning by assigning the source value to another constant. JavaScript const copiedObject = sourceObject console.log('sourceObject', sourceObject.l1_2) // My original object --> ✔️ clonedObject.l1_2 = 'My cloned object' console.log('clonedObject', clonedObject.l1_2) // My original object --> ✔️ console.log('sourceObject', sourceObject.l1_2) // My original object --> ❌ As I said before, when I change the property l1_2 on the cloned object, the value also changes on the source object. Using this strategy, you are not copying the object at all. Using Spread Operator This time I’ll use the spread operator, which 'returns' every element in the object individually. JavaScript console.log('sourceObject l1_2', sourceObject.l1_2) // My original object --> ✔️ console.log('sourceObject l1_1.l2_1', sourceObject.l1_1.l2_1) // 123 --> ✔️ const clonedObject = { ...sourceObject } clonedObject.l1_2 = 'My cloned object' console.log('clonedObject', clonedObject.l1_2) // My cloned object --> ✔️ console.log('sourceObject', sourceObject.l1_2) // My original object --> ✔️ clonedObject.l1_1.l2_1 = '321' console.log('clonedObject l1_1.l2_1', clonedObject.l1_1.l2_1) // 321 --> ✔️ console.log('sourceObject l1_1.l2_1', sourceObject.l1_1.l2_1) // 321 --> ❌️ // Should keep returning 123 if the clone was complete Lodash to the Rescue Lodash is a modular utility library that adds many functionalities, and one of them is cloneDeep, which does exactly what we need to clone (deep) an object through nested properties, keeping all value types, even functions. JavaScript import { cloneDeep } from 'lodash' const clonedObject = cloneDeep(sourceObject) console.log('clonedObject l1_1.l2_3.l3_3', clonedObject.l1_1.l2_3.l3_3) // function l3_3() {} --> ✔️ console.log('sourceObject l1_1.l2_3.l3_3', sourceObject.l1_1.l2_3.l3_3) // function l3_3() {} --> ✔️ Performance We’ll copy the source object 10.000 times using each method to compare the time elapsed. Compare memory usage is no sense because Object.assign and Spread Operator method is not copying nested property by value. The results in my browser are the following: * Object.assign clone elapsed time: 4ms* Spread operator clone elapsed time: 22ms* JSON clone elapsed time: 47ms* Lodash clone elapsed time: 92ms As you can see, if you only need to do a shallow clone Object.assign is the faster solution over the spread operator, and if you only need to clone values in nested properties (not functions or symbols), JSON.parse(JSON.stringify()) could be a faster solution. But if you want to make sure that all values are copied, you must use Lodash or a similar solution.
With data everywhere around, we should know how to graphically represent it to better (and faster) understand what it tells us. One of the most common data visualization techniques is column charts, and I want to show you how you can easily create interactive ones using JavaScript. A column chart is a simple yet powerful way to display data when you need to compare values. From this tutorial, you will learn to make its different variations — basic single-series, multi-series, stacked, and 100% stacked column graphs — and apply effective customizations in a few more lines of JS code. As a cricket fan, I thoroughly watched the ICC Men’s T20 World Cup held last month in Australia. I decided to use some data related to the championship for illustrative visualizations. JavaScript column charts built throughout this tutorial will let us look into the batting statistics and, more precisely, the number of runs scored by the top 10 batsmen at the tournament. Let’s have fun learning! 1. Basic JS Column Chart A basic JavaScript column chart can be built very easily in just four steps. Let me show you what is to be done in each of these steps, along with explaining every line of code that I will write. Create a container. Include script files. Prepare data. Write a visualization code. A. Create a Container First of all, you need to set up a place for your chart. If you already have a web page where you want to put it, open your HTML file, and if not, create one from scratch. Then add a block-level HTML element and give it an ID. Also, set its width, height, and other styling parameters to suit your requirements. I have created a very basic HTML page, added a <div> element with the “container” id, and specified its width and height as 100% so that the resulting JS-based column chart fills the whole page: HTML <html> <head> <title>JavaScript Column Chart</title> <style type="text/css"> html, body, #container { width: 100%; height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="container"></div> </body> </html> B. Include Script Files The easiest way to quickly create an interactive chart for the web is to use one of the existing JavaScript charting libraries. They are sets of pre-written charting code, which makes it possible to build data visualizations with minimal additional coding efforts. The steps for creating a column chart are basically the same regardless of the specific library. Whichever you opt for, include it in your web page by referencing its JavaScript file(s) in the <script> tag in the <head> section. Then add another <script> tag anywhere in the <head> or <body> section — it’s where the column charting code will be placed. In this tutorial, to illustrate the process, I will be using one called AnyChart. It is a lightweight JS charting library with detailed documentation and many examples, free for non-commercial purposes. So, I include its base module: HTML <html> <head> <title>JavaScript Column Chart</title> <style type="text/css"> html, body, #container { width: 100%; height: 100%; margin: 0; padding: 0; } </style> </head> <body> <div id="container"></div> </body> </html> C. Prepare Data Next, prepare the data you want to visualize in a column chart. I collected the total runs statistics for the ICC Men's T20 World Cup’s top 10 scorers from ESPNcricinfo and collated them in a simple JavaScript multidimensional array. (Of course, you may use a different data format like JSON, XML, CSV, and so on.) JavaScript [ ["Virat Kohli", "296", "India"], ["Max O'Dowd", "242", "Netherlands"], ["Suryakumar Yadav", "239", "India"], ["JD Butler", "225", "England"], ["Kusal Mendis", "223", "Sri Lanka"], ["Sikandar Raza", "219", "Zimbabwe"], ["Pathum Nissanka", "214", "Sri Lanka"], ["AD Hales", "212", "England"], ["Lorkan Tucker", "204", "Ireland"], ["Glenn Phillips", "201", "New Zealand"] ] D. Write a Visualization Code The ground is set, the players are ready, the toss is done, and now it is time for the match to begin! Creating a column chart with a JS charting library is like hitting a sixer in cricket — less effort and more reward. Let me show you how to get it up and running by writing a few lines of JavaScript code. The first thing that I do is add the anychart.onDocumentReady() function inside my <script> tag in the <body> section. Everything else will go into this function. HTML <script> anychart.onDocumentReady(function() { // The following JS code to create a column chart. }); </script> Then I create a JS column chart instance using the inbuilt function and add a series with the prepared data. JavaScript // create a column chart var chart = anychart.column(); // create a data series var series = chart.column([ ["Virat Kohli", "296", "India"], ["Max O'Dowd", "242", "Netherlands"], ["Suryakumar Yadav", "239", "India"], ["JD Butler", "225", "England"], ["Kusal Mendis", "223", "Sri Lanka"], ["Sikandar Raza", "219", "Zimbabwe"], ["Pathum Nissanka", "214", "Sri Lanka"], ["AD Hales", "212", "England"], ["Lorkan Tucker", "204", "Ireland"], ["Glenn Phillips", "201", "New Zealand"] ]); It is always a good practice to add titles to the axes and chart itself to make it obvious what is represented. Let’s set these: JavaScript // add axis titles chart.xAxis().title("Batsman"); chart.yAxis().title("Number of runs"); // add a chart title chart.title("Top 10 Run Scorers at ICC Men's T20 World Cup 2022"); Lastly, I set the container element — here’s where its ID is needed — and make the resulting column chart visualization appear. JavaScript // set the container element chart.container("container"); // display the chart chart.draw(); Just in case, here’s how the entire JS code within the <script> tag currently looks: JavaScript anychart.onDocumentReady(function () { // create a column chart var chart = anychart.column(); // create a data series var series = chart.column([ ["Virat Kohli", "296", "India"], ["Max O'Dowd", "242", "Netherlands"], ["Suryakumar Yadav", "239", "India"], ["JD Butler", "225", "England"], ["Kusal Mendis", "223", "Sri Lanka"], ["Sikandar Raza", "219", "Zimbabwe"], ["Pathum Nissanka", "214", "Sri Lanka"], ["AD Hales", "212", "England"], ["Lorkan Tucker", "204", "Ireland"], ["Glenn Phillips", "201", "New Zealand"] ]); // add axis titles chart.xAxis().title("Batsman"); chart.yAxis().title("Number of runs"); // add a chart title chart.title("Top 10 Run Scorers at ICC Men's T20 World Cup 2022"); // set the container element chart.container("container"); // display the chart chart.draw(); }); Result 1: Column Chart Voilà! A functional basic JavaScript column chart is done! You can find the interactive version of this diagram with the full source code on Playground. Column charts are designed to facilitate comparisons. Here, I can see how Virat Kohli is quite ahead of the pack, with the rest near each other. But it’s just the beginning! Now I also wonder how each of these players scored those runs. More precisely, I want to find out how many runs out of the total are scored by hitting a six, a four, or by running between the wickets. A multi-series column chart or a stacked column chart would perfectly represent that. So, let’s dive deeper into column charting in JS, and I will show you how to make both and then beautify the entire visualization! 2. Basic JS Multi-Series Column Chart Just like a single-series column chart, a multi-series column chart can be made using JavaScript quickly and easily. Actually, the base remains the same, and you just need to change the data. Add Multi-Series Data Instead of totals, let’s add the number of runs scored by hitting (1) sixes, (2) fours, and (3) running between the wickets for each of the top 10 scorers. I take this data from the same source, ESPNcricinfo, and create a data set: JavaScript var dataSet = anychart.data.set([ ["Virat Kohli", "India", "148", "100", "48"], ["Max O'Dowd", "Netherlands", "106", "88", "48"], ["Suryakumar Yadav", "India", "81", "104", "54"], ["JD Butler", "England", "87", "96", "42"], ["Kusal Mendis", "Sri Lanka", "95", "68", "60"], ["Sikandar Raza", "Zimbabwe", "89", "64", "66"], ["Pathum Nissanka", "Sri Lanka", "114", "52", "48"], ["AD Hales", "England", "76", "76", "60"], ["Lorkan Tucker", "Ireland", "104", "76", "24"], ["Glenn Phillips", "New Zealand", "77", "76", "48"] ]); Map the Data Next, it is necessary to map this data to the three series, each indicating a category. The first series indicates the runs scored by running. One more series indicates the runs scored by hitting fours. And the third series indicates the runs scored by hitting sixes. JavaScript var firstSeriesData = dataSet.mapAs({x: 0, value: 4}); var secondSeriesData = dataSet.mapAs({x: 0, value: 3}); var thirdSeriesData = dataSet.mapAs({x: 0, value: 2}); Create the Series Now it’s time to create the three series with the respectively mapped data. JavaScript var series; series = chart.column(firstSeriesData); series = chart.column(secondSeriesData); series = chart.column(thirdSeriesData); Result 2: Multi-Series Column Chart And a basic JS multi-series column chart with grouped series is ready! You can check out its interactive version with the full source code on Playground. A grouped multi-series column chart greatly represents a breakdown by score category. But totals are also worth looking at. So, let’s create stacked columns now! 3. Basic JS Stacked Column Chart To turn grouped columns into a stacked column chart, just one quick line of JavaScript code is more than enough. Set the Value Stacking Mode Enable the value stacking mode on the Y-scale: JavaScript chart.yScale().stackMode("value"); Result 3: Stacked Column Chart There you go! Now you’ve got a basic JS stacked column chart! Its interactive visualization is available on Playground with the full source code. Now, let’s beautify it! 4. Custom JS Stacked Column Chart Depending on exactly how you want to customize your JavaScript-based stacked column chart visualization, you may want to modify different things. I will show you some important but still easy-to-implement adjustments. Adjust the Series When you hover over the interactive columns, the tooltip automatically shows the values for each category. But which one is where? Let’s name the series, and everything will become clear! At the same time, why don’t we play with the colors a little? I will paint the series in the colors of the ICC T20 World Cup 2022’s official logo. This will make the column chart look so much more personalized and aesthetically pleasing. For this, I create a function that will accept each series, its name, and the color associated with it. I will also add a stroke attribute in the function, which will be applied to each series for creating a sort of padding between each category. JavaScript var setupSeries = function (series, name, color) { series.name(name).stroke("2 #fff 1").fill(color); }; Now, I set up the three series with the function just created and give each of the series the respective name and color. JavaScript // store the series var series; // create the first series with the function series = chart.column(firstSeriesData); setupSeries(series, "Runs scored with Sixes", "#eb2362"); // create the second series with the function series = chart.column(secondSeriesData); setupSeries(series, "Runs scored with Fours", "#00b1e5"); // create the third series with the function series = chart.column(thirdSeriesData); setupSeries(series, "Running between the wickets", "#0f0449"); Add a Legend To further improve the legibility of the column chart, it is a good idea to add a legend that will show which color indicates which category. This can be done easily by just enabling the legend. I’ll just also add some font size and padding customizations. JavaScript chart.legend().enabled(true).fontSize(14).padding([10, 0, 0, 0]); Check it out; you can hide/show a specific category by clicking on the respective legend item. Enhance the Labels, Tooltip, and Title As you can see, some of the names of the batsmen are not visible on the X-axis. To rectify that, I rotate the labels so that each name can be seen. JavaScript chart.xAxis().labels().rotation(-90); The default column chart tooltip shows individual category values but not the totals. Moreover, totals are not included in the data set. But it’s easy to make them calculated automatically and then put them somewhere, for example, in the tooltip header. JavaScript chart.tooltip().titleFormat(function () { return this.x + " — " + this.points[0].getStat("categoryYSum"); }); Also, it is possible to display the values of all the categories together in the tooltip using the union mode. JavaScript chart.tooltip().displayMode("union"); Finally, let’s make the chart title a bit larger, change its font color, and add some padding. JavaScript chart.title().fontSize(20).fontColor("#2b2b2b").padding([5, 0, 0, 0]); Result 4: Customized Stacked Column Chart That’s it! The stacked column chart is all customized. Have a look at how stunning and insightful it has become! And feel free to see this interactive JS-based stacked column chart on Playground where you can also further play with its code, add your data, and so on. Looks lovely, doesn’t it? And I can distinctly see both total scores and how some batsmen have done a lot of running while some have accumulated more runs with their hits. 5. JS 100% Stacked Column Chart Finally, I want to demonstrate how you can create a 100% stacked column chart representation that can help compare individual categories across all data points in an easier manner. Switch the Column Stacking Mode Just change the stacking mode from value to percent, and your stacked column chart will become a 100% stacked column chart: JavaScript chart.yScale().stackMode("percent"); Result 5: 100% Stacked Column Chart And it’s done, the final data visualization example in this tutorial! You are welcome to check out this JavaScript-based percent stacked column chart variation with the entire code on Playground. Conclusion In this tutorial, I showed you how to create JavaScript (HTML5) column charts in different variations, such as a regular, single-series column chart, a multi-series grouped column chart, a value-stacked column chart, and a 100% stacked column chart. You also saw how you can customize them. I used the AnyChart JavaScript charting library, but there are multiple others out there at your disposal. A good thing is that fundamentally the process is similar to anyone. So you can use whichever suits your needs. Let me know if you have any questions or suggestions. As the batting scores show you, the total figures include plenty of boundaries but quite a lot of running as well. So, go on then, work hard and knock it out of the ground with more such beautiful column charts and other data visualizations!
This is the first of a three-part app development workshop series designed to help developers understand technologies like Node.js, GraphQL, React, Netlify, and JavaScript to kickstart their app development portfolio. In this post, we’ll cover the fundamental concepts of website applications and introduce DataStax Astra DB as your free, fast, always-on database based on Apache Cassandra®. In the U.S. we spend almost 88% of our mobile internet time buried in apps like Facebook, Instagram, TikTok, and games. With nearly a million new apps released each year and 218 billion app downloads in 2020, learning how to build them is an essential step in any front-end developer’s career. So how can you start building apps? As a modern app developer, you’re spoiled for choice with multi-cloud platforms and open-source frameworks that do all the heavy lifting for you. Suppose you learn the basics and leverage the right tools. In that case, you can go from developing simple to-do lists to a full-stack Netflix clone — which is precisely what we’ll be covering in our application development workshop series. This first workshop is about building a website application to put you on the right track. You’ll learn the fundamentals of web apps, become familiar with popular languages (like JavaScript), and then get a pre-coded to-do list app that you’ll learn how to modify and deploy. It’ll take you less than three hours to complete, and all you need is a web browser and an internet connection. Let’s get started. The Basics of Web App Development A website application (or web app) is software that runs on a remote server and can be accessed using a web browser on any device. Think of apps like Slack, Gmail, Google Docs, and Twitter, for example. Unlike native apps, which are installed directly on a device and designed for specific operating systems, web apps can reuse the same code and adapt their interface to any mobile device, laptop, or tablet. While native apps perform much faster, they’re also expensive to develop because you need to learn different languages and frameworks for each platform or device. Web apps, on the other hand, can be “built once and reused forever,” and are vastly simpler to launch, manage and iterate. When developing a web app, you’ll typically use the following architecture: Figure 1: Architecture of a typical website application. The client is your device’s web browser, which you use to access the app. The front end is what the user interacts with, and is basically a web server that relies on three main technologies: HTML, CSS, and JavaScript. The backend is what interacts with the webserver and stores all the database drivers, APIs, and microservices that bridge the front end with the backend. The data layer is where you store the states of your app. This can be in a filesystem, external storage, document-oriented software, or a database. A popular database you might already be familiar with is Apache Cassandra®, which powers high-performing applications for thousands of companies including Hulu, Netflix, Spotify, and Apple. While this free, open-source database is known for its high availability, scalability, and resilience; the downside is that it’s also notoriously complex to set up and manage. This complexity is an ongoing theme when working with the data layer. As a developer, you need just four operations to interact with your database: create, read, update, and delete. But to execute them, you first have to learn the language for the database you’re using. For example, you’d need Cassandra Query Language (CQL) to interact with a Cassandra database. What’s more, you’d also need to learn how to design the data model (schema) so you can properly format and organize the data stored in your database. It’s a steep learning curve for a new app developer, which is why DataStax built Astra DB, the serverless Cassandra-as-a-Service, as part of our mission to connect every developer to the power of Cassandra. Simplify Cassandra App Development With Astra DB Astra DB is the simplest way for developers to back their applications with cloud-native Cassandra, allowing them to: Deploy modern apps faster without the complexities of installing, managing, or scaling Cassandra. Interact with your database using multiple APIs to avoid data modelling. Bake in security from the ground up with encrypted data and JSON web token (JWT) based authentication for secure communication with your database. Choose whether to deploy your Astra DB on Azure, GCP, or AWS. Autoscale database resources are based on traffic and app requirements so you only pay for what you use. As a developer, you can create an account on Astra DB for free. You get 3.5 million queries and 40 GB each month, and when you’re ready to scale, you can simply pay as you go. Astra DB doesn’t just give you a database, it also gives you a collection of APIs that you can use to interact with your database out of the box. This API layer that sits between your app and your Astra DB is called Stargate. Stargate helps you streamline app development with Cassandra using popular APIs: REST provides a common gateway so you can access your data using a familiar interface through RESTful APIs for any Cassandra database. Document (JSON) is a documents API that lets you save and search schemaless JSON documents in Cassandra (with no data modelling needed). GraphQL is a query language for APIs that lets you insert, query, and change data within the database (without writing in CQL). All of this means fewer languages and frameworks for you to learn and a shorter time to launch. Think of AstraDB as your own personal Samwise Gamgee, with all kinds of useful tools in its bag to make your app development journey easier. Build Your First Web App With JS, Node.JS, and Astra DB There’s no better exercise to get you started as an app developer than building a to-do list. The concepts and techniques you’ll learn in our first workshop are fundamental to building any web app and will put you on track to creating more advanced apps yourself. So, in this workshop you’ll learn how to: Set up a free Astra DB instance Run the web-based IDE Gitpod Interact with the database using APIs Build a to-do list app using React You don’t have to install anything and the technologies involved are all open-source and free to use. Aside from Astra DB, here’s a quick intro to the other technologies we’ll cover in this first workshop: Gitpod is a cloud-based integrated development environment (IDE) powered by VS Code that lets you create ready-made dev environments and edit your code directly in your browser. Node.js is a runtime environment that executes JavaScript outside of a browser to let you generate dynamic page content and interact with the data in your database. React is a JavaScript library to create interactive user interfaces that easily adapt across most browsers and devices. To give you the bigger picture, here’s the architecture we’ll be following to build the to-do list app: To get started, simply sign up for your free Astra DB account, then head over to the workshop video on YouTube. For the source code, slides, exercises, and step-by-step guide go to our DataStax Developers repo on GitHub. When you’ve completed your first app and are ready for the next step in your app development journey, dig into our second workshop on building a TikTok clone!
What is Node.js? Why use Node.js? Let's dig deeper and find out more details to help you decide whether this environment is the right choice for your app development. Are you developing an app from scratch? Want your app to be fully functional? If so, you need to choose the right tools, platforms, and languages. If you're working on a web application, you're undoubtedly weighing the benefits and drawbacks of basing your stack on JavaScript and the tools that support it. And, once you start researching development platforms, you'll almost certainly come across Node.js. What Is Node.js? Node.js is a cross-platform open-source runtime environment and library used to run web applications outside the client's browser. Initially, it was created by Ryan Dahl in 2009. Dahl was inspired to create it after seeing a file upload progress bar on Flickr and being dissatisfied with existing solutions for building web applications. So, he decided to develop an environment that would be lightweight and easy to use. And that's how it was born. Now, you are probably wondering what to use node js for. It is used for server-side programming and primarily for non-blocking, event-driven servers like typical websites and back-end API services. Every browser has its JavaScript engine, and Node.js is based on the V8 JavaScript engine in Google Chrome. Is Node.js a Programming Language? It is necessary to understand that Node.js is not a framework or a library, as with traditional application software, but rather a runtime environment. A runtime environment (RTE) is a collection of web APIs that a developer can use to create a code and a JavaScript engine to parse that code. This makes it lightweight, versatile, and simple to deploy, all of which will assist in optimizing and accelerating your application project. After this brief crash course, you'll be ready to move on and learn why using Node.js for your app development out of the available tech stacks is a good idea. 5 Reasons to Use Node.js for App Development Node.js offers the potential for rapid development and competes with Java, Go, Ruby on Rails, and Python. Here are five benefits to answer the question of what to use Node.js for. 1. Language Sharing Across the Stack With Node.js, JavaScript is used for front-end and back-end development, making the language more consistent across the entire application. This contrasts with most applications, which use different languages for the front end (like HTML, CSS, and JavaScript) and back end (like PHP, Ruby on Rails, or Java). When using Node.js, you may exchange code between client and server apps. You can use JavaScript for the entire development process, allowing for improved communication between back-end and front-end teams. This also makes full-stack development more straightforward and accessible, as you no longer need to locate an engineer fluent in numerous programming languages. Last but not least, while many Node.js developers choose to work with JavaScript because it is dynamically typed, those who prefer static typing can utilize TypeScript. Node.js allows you to select either option to tailor your working environment to your specific requirements. 2. Rapid Development The JavaScript language is relatively simple to learn, and every front-end developer knows it. This makes for a very short learning curve when moving from front-end to full-stack development using Node.js. Node.js makes it easy to get started with development. Its servers may be set up quickly, and a simple "Hello World" API can be up and running in under a minute. This runtime environment is also ideal for developers constructing microservice environments since they link multiple APIs together. This is due to how simple it is to create an API in Node. It is also a good choice for prototyping solutions and architectures because it allows quick and easy experimentation. Once you're farther into the development cycle, you can switch between dynamic and static typing as needed, providing freedom over how various components of your system are constructed. You can use as many libraries as your project requires. You either create these or download and use existing ones via the Node Package Manager. 3. The Node Package Manager The Node Package Manager (NPM) is one of the most significant advantages. NPM allows you to download and use code packages other developers provide in your projects. As a result, you won't have to develop nearly as much code from scratch. Node.js hosts the most extensive software library registry in the world. It contains over 1.3 million packages in the main registry, all of which have been created by the Node.js community, making it easy to find solutions to various problems you may encounter while developing your app. NPM makes it simple to manage application dependencies by installing the library's code and all dependents. And when combined with GitHub, the world's largest code repository, you have access to an immense amount of code that can be used to solve various problems. 4. Single-Threaded Event Loop Architecture Node.js is known for using a single-threaded event loop architecture, which is ideal for microservices. When a Node.js app starts, it initializes the event loop and then executes a single instruction at a time. This approach has several benefits. It dramatically simplifies development since developers don't need to worry about managing multiple threads. It improves performance because it can process more requests simultaneously than other architectures. It makes for more scalable apps since individual parts can be scaled down as needed without affecting the entire system. This architecture is ideal for real-time applications like chatbots, which need to respond immediately to user input. 5. Native Support in AWS A host is required for all web applications, and Amazon Web Services (AWS) is the most used hosting platform, accounting for 32% of the cloud market. AWS supports Node.js natively and is intimately integrated with the platform. Cloud9, an Amazon in-browser Integrated Development Environment (IDE), allows users to write and change code in their browser. It is compatible with Node.js and has one of the lowest entry barriers for a scalable microservice. You can utilize JavaScript with AWS tools like the Cloud9 IDE and Node.js with Amazon's Internet of Things (IoT) SDK and the AWS Cloud Development Kit for JavaScript. The SDK also supports TypeScript. Why use Node.js? First, it makes full-stack development easier due to language sharing across the stack. Also, app development is rapid in this runtime environment, mainly because the most extensive software library registry in the world is hosted by it. In other words, whenever you encounter a problem, you will likely be able to find the solution in the library. Last but not least, did you know that some of the most popular apps use Node.js at their core? This has allowed them to handle millions of visits and develop their features over time. Let's check them out! Examples of Node.js Apps Node.js is used to create scalable desktop and mobile apps and web and IoT projects that need to handle large amounts of connections without experiencing any issues. For that reason, some of the most popular apps switched to Node.js after years of using other runtime environments. If you're still wondering why you should use Node.js, look no further. Netflix, Uber, and other popular apps use it, so there must be something to it! 1. Netflix Netflix is the world's leading streaming service, with over 150 million subscribers in over 190 countries. It offers an extensive library of films and TV series, including those produced in-house. Also, Netflix is known for investing vast sums of money into improving and developing its services. Netflix spends $150 million annually on improving its recommendation system, and the company spent $1.5 billion on development in 2019. Also, Netflix has been spending roughly $9.7 million per month on AWS since 2016. There's no better choice than Node.js when streaming enormous volumes of information to thousands of users simultaneously. It has helped Netflix handle the massive amount of traffic it receives. So, if you're wondering why you should use Node.js, Netflix is a terrific example of how this environment fosters business growth and customer happiness. 2. Twitter Twitter is a top-rated social networking platform with over 330 million monthly active users. It is also one of the ten most visited websites in the world. Since its launch in 2006, Twitter has undergone several redesigns and changes. The company decided to switch to Node.js in 2017, and since Twitter's developers began using Node.js, they've been pleased with its development speed. The main reason for the switch was Twitter's need for a language that would allow them to make changes rapidly and deploy them immediately. Node.js fit that bill perfectly, and since then, it has helped the company move faster and scale more easily. 3. Uber Uber is a ride-hailing service present in over 700 cities in 65 countries. It offers its services to over 110 million users and has over 3 million drivers. Since its founding in 2009, Uber has dominated the car-sharing market. Uber decided to use Node.js to build its core, make its app more responsive, and improve its real-time capabilities. Node.js has helped the company handle massive traffic and scale quickly. 4. Slack Slack is a collaboration tool that helps people communicate and work together more efficiently. It has over 12 million active users and is used by some of the world's leading companies, including NASA, Airbnb, and eBay. Slack decided to use Node.js because of its event-based architecture, which makes it ideal for real-time applications. The company needed an environment allowing them to handle many concurrent users and fit the bill perfectly. 5. Coursera Coursera is an online course provider that partners with top universities and organizations to offer online courses, certificates, and degrees. It has over 3,000 courses and numerous degree and master's programs. The company was founded in 2012 by two Stanford professors and now has over 33 million users worldwide. Since its launch, Coursera has been built entirely on Node.js. The company needed a JavaScript framework allowing fast development and easy scalability. Node.js was the obvious choice since it is lightweight and offers a wealth of modules that can be used to add various features to an app. Conclusion As you can see, there are many reasons to use Node.js for web and app development. It is fast, scalable, and has a vast ecosystem of modules that make development easier. Also, it is supported by Amazon Web Services and used by some of the most popular apps in the world. And regarding what to use Node js for? If you're looking for a JavaScript framework to help you develop an app quickly and easily, Node.js is the obvious choice. But keep this in mind—unless you have a team of experts and UX/UI designers, it won't be easy to take advantage of this technology at its full potential.
Data visualization is required for the UI/dashboard of any program that focuses on data. It can be challenging to create accurate charts and infographics, but fortunately, many JavaScript libraries are available. However, there can be an overwhelming variety of options, each with advantages and disadvantages. You can use this article to choose a JavaScript data visualization library and learn more about its features. Here are the most important factors to consider while choosing the right JavaScript data visualization library for your project. Compatibility With Browsers and Devices One of the most important indicators of an effective data visualization library is its accessibility to everyone. This can be accomplished in two ways: first, by having an easy-to-use interface, and second, by being accessible across all platforms. You can choose a solution with a fully responsive design and mobile compatibility. Versatility of Tools Data preparation is the first functionality that must be covered for proper data processing to provide meaningful visualizations with genuinely helpful information. Advanced and predictive analytics are also crucial for data visualization libraries to maximize your data and improve your ability to predict the future. Capacity for Data Processing Establishing that the chosen solution can give an optimal performance while managing a significant amount of data is important. Pay special attention to how well a data visualization library can manage multiple sources. The tool must be able to import any type of file and quickly connect to different databases. Adaptability for Every Need Every business has unique requirements and qualities. So, it is good to find a flexible solution that can change to meet the needs of a specific company. Additionally, a decent data visualization tool must be adaptable to the organization's industry. For example, retail businesses don't have the same requirements as financial experts or government agencies. Convenient Exporting If you are creating dashboards for business users, they might want to export their data and charts to PDF or images. It will be ideal if the data visualization library you use has an export function built in from the start. Helpful Support When you encounter a problem, you may want outside assistance to overcome it. Support might take many different shapes, such as personal consultation, tech support, or community forums. The majority of general questions are already answered in popular data visualization libraries through documentation, tutorials, or FAQ sections. These are some well-known data visualization libraries that would be a wonderful asset to any data-intensive application. D3.js Effective for creating dynamic and interactive data visualizations for web browsers. It builds graphs, maps, and pie charts using current web standards. D3.js offers tools that help to create charts incrementally from the ground up. This makes it considerably more challenging to rapidly design a basic chart using D3.js because you need to understand how its functions and modules operate. Webix JavaScript Charts Library Graphing and charting framework used to create exceptional analytical online apps and unique user interfaces. It enables the implementation of dynamic data visualization with fluid animation and several interactive elements. The interactive UI controls include 14 types of charts and data tools, such as sorting, filtering, and grouping. The data export feature converts information into PDF, PNG, Excel, and CSV formats. DHTMLX JavaScript Charts Library A flexible JavaScript chart library with countless settings, customization options, and code snippets. Chart configuration can be instantly adjusted thanks to the DHTMLX rich API. You may build an entirely online application by combining DHTMLX Charts with other UI widgets. Data from Charts and DHTMLX Grid can be synchronized for seamless updates. Chart.js It provides clear, stylish, and captivating charts that you may easily use in your application. It offers nine different chart types, which are all, by default, adaptive and accessible. Plus, it features labels, legends, hover pop-ups, and series toggling that are all customizable. This library could be great for you if you regularly deal with large datasets. Highcharts Highcharts is a library for creating charts written in JavaScript, which makes it easy to add interactive, animated charts to a website or web application. At the moment, charts support a large number of linear, circular, column scattering charts and many other types. FusionCharts FusionCharts is another good library for building interactive graphs and charts, with hundreds of ready-made examples. Graphs from FusionCharts support data in both JSON and XML formats. Thanks to the ready-to-use chart examples, industry-specific dashboards, and even data stories that are available with source code, you can start using it right away. Conclusion Given how crucial data visualization is for web applications, JavaScript data visualization frameworks often have too many options. Choosing the perfect one depends on how well it integrates with your specific application and your intended use case.
JavaScript is a very popular and powerful programming language that’s used with HTML and CSS to create the front end of a website. There are many frameworks of JavaScript, which are frontend and backend. In this article, we’ll discuss the 5 best JavaScript web development frameworks. What’s a JavaScript Framework? The JavaScript framework is a pre-written collection of several JavaScript libraries that are used to perform desired tasks. There’s a difference between a JavaScript framework and a library. Frameworks are the blueprints to make a project while a library is a pre-built project. 5 Best JavaScript Web Development Frameworks Following are some of the best JavaScript web development frameworks: 1. React React is a JavaScript library. React was maintained and created by Facebook on May 29, 2013. It’s a front-end web development framework that provides a better UX (User Experience) than any other framework or library. There are many reasons to use React as your front-end framework over any other framework. Features of React Reusable code called components: In React you define a part of a web page as a component and then use it as many times as you want without needing to write the code again and again. Built-in Debugging tools: One of the main features of React is its debugging tools that help developers easily debug their apps. There’s also a debugging extension of React for Chrome. Easy to learn and use: React is very easy to learn as compared to any other framework or library. Virtual DOM Availability: React uses a Virtual DOM called ReactDOM. That makes the React app fast and provides a better UX. JSX: In React, instead of using HTML, we use JSX, which is quite familiar to HTML and works nearly the same as HTML. 2. AngularJS AngularJS is a free, open-source, and powerful web development framework written in JavaScript. It was developed, maintained, and released by Google on September 14, 2016. Like React, it’s mostly used for developing single-page applications. Even though Angular is a front-end framework, it's still compared to Django, which is a backend framework. Features of AngularJS Two-way binding: AngularJS uses a two-way binding that enables us to make changes to the basic data using a user interface. Huge Support: As we have discussed earlier, Angular is created and maintained by Google; hence the support for Angular is very huge. There are several communities out there to help, including Google Groups. Real-time testing: AngularJS provides real-time testing for testing out your components. It makes it very easy for you to test your controllers, filters, and directives. POJO model: AngularJS makes good use of the POJO model. It stands for Plain Old Java Object Model. It’s mostly used to improve the readability of the code. Routing: As AngularJS is used to build single-page applications, that’s why routing is used. So that you don’t see a refresh whenever a new page loads. For routing, AngularJS uses a module called ngRoute. 3. Node.js Node.js is a server-side library written in JavaScirpt. It runs JavaScript out of the browser on the server. Features of Node.js Cross-platform compatibility: Node.js is a cross-platform development framework which means that you can use it to make applications for different platforms, including Windows, Linux, and Mac. Fast caching for better speed: Node.js uses caching to apply faster. The data that’s mostly used is stored in the storage so that the client doesn’t have to ask to the server every time. Efficient and scalable: Node.js is very efficient and scalable. That's why many big companies use it for their backend. Recently Netflix shifted from Java to Node.js, which helped them a lot to save their resources. 4. EmberJS EmberJS is another free, open-source, front-end web development framework written in JavaScript. It’s also used to create single-page web applications. Some of the famous companies using EmberJs are Twitch, LinkedIn, Digital Ocean, etc. Features of Ember.js Ember CLI: EmberJS comes with a pre-built CLI, which provides features like auto-refresh, build, and serving the files easily. You can install EmberCLI by using this command $ npm install -g ember-CLI Community support: Community support for EmberJS is huge. You can find answers to any kind of problem regarding EmberJS on StackOverflow and other forums. Even the documentation for EmberJS is quite helpful and beginner-friendly. Powerful add-ons and plugins: Any pre-written code or packages that provide more features to developers are called add-ons or plugins. ExpressJS comes with tons of powerful add-ons that can be installed using npm. Ember Octane Edition: EmberJS is already a very efficient web development framework. But it was missing some modern-day features when the Ember Octane was released. According to Ember Team, “you get everything you need to build your app using Octane.” 5. ExpressJS ExpressJS is a free and open-source application for Node.js that’s mostly used to make APIs and Rest APIs. ExpressJS or Express is released under the MIT license. It’s used for MERN, MEVN, and MEAN Stacks. Features of ExpressJS Fast: ExpressJS is a very fast framework as compared to any other server-side framework. It uses the Google V8 engine for better speed and performance. Debugging is easy: In ExpressJS, debugging is very easy due to using debugging modules internally. Tons of Templates: ExpressJS provides tons of templates for static use. A template engine is used for using static templates in your app. Conclusion In this article, we have discussed the 5 best JavaScript web development frameworks. All of these frameworks or libraries are used by thousands of famous websites. We have discussed both front-end and back-end development frameworks. Now, it depends upon you which one is better for you. What do you think other frameworks should be on this list? Let us know in the comments.
Document generation is a very common requirement in the life of a developer. Whether it is an e-commerce site, Management app, or anything. It can be invoice generation, insurance document preparation, doctor's prescription, HR Offer generation, and Payslip generation and you could think of tons of use cases. There always will be a need for document generation. From a developer's perspective, there are a few common approaches to getting this job done. Create HTML elements and print them to generate the documents Using some library to generate the documents Letting the server handle document generation based on a static template These approaches didn't help me. The clients want to have their documents customized by themself. I have been searching for an approach and found eDocGen as a single-point solution. Unlike other services, eDocGen provides RestAPI that can be integrated into our application. In this article, we will discuss how we can integrate eDocGen into our js application to generate documents from various data formats like JSON/XML/Database schema. Please get your free trial to get started with the coding. Let's dive in and write code. Project Setup For the demo purpose, I have created a sample js application that runs on Node.js. Please follow the step below to set up a coding playground for us. Step 1: Use npm init to create package.json Step 2: Add axios, form-data, request, xhr2 dependencies needed for developing this application using npm install axios form-data request xhr2 Step 3: We need an index file that will act as the starting point of our application. Create an index.js file in the root directory and modify package.json like below. JSON "scripts": { "start": "node index.js" } Now we have a basic application to start with. End of these steps, the package.json should look like something below. JSON { "name": "nodejs-multiple-upload-files", "version": "1.0.0", "main": "index.js", "scripts": { "start": "node index.js" }, "dependencies": { "axios": "^0.27.2", "form-data": "^4.0.0", "request": "^2.88.2", "xhr2": "^0.2.1" } } Login Though the article is about document generation, we need to log in to get our access token. It's a typical JWT token that will be used for authorizing the document generation API. JavaScript var XMLHttpRequest = require("xhr2"); var xhr = new XMLHttpRequest(); module.exports.getToken = function (callback) { var data = JSON.stringify({ username: "<your username>", password: "<password>", }); xhr.addEventListener("readystatechange", function () { if (this.readyState === 4) { token = JSON.parse(this.responseText).token; console.log("User Token", token); callback(token); } }); xhr.open("POST", "https://app.edocgen.com/login"); xhr.setRequestHeader("content-type", "application/json"); xhr.setRequestHeader("cache-control", "no-cache"); xhr.send(data); }; We can cache the token in the application for a time period less than the expiration time and use it to generate documents or upload templates. After the expiration time, we can refresh the token. The cache can be Redis or an in-memory cache. It's up to your application design. Template Design As explained above, eDocGen lets the users customize and upload the templates. But how will the data be mapped dynamically? There are certain rules that map the data to the document. We will see how to create a template with the rules. Take a look at this document. eDocGen uses tags that are enclosed by {} for the dynamic fields. We can dynamically add text, logos, tables, conditional statements, mathematical calculations, etc. For example, in the image above, String fields: {Invoice_Number} and {Invoice_Date} are configured to be replaced as text in the template. Anything inside {} in the template will be matched with input data and replaced. Dynamic Tables: Dynamic tables would be a go-on option when there is an array of data that needs to be looped and replaced in a table. The row in the table starts with {#tablename} and ends with {/tablename}. In the example above, a row in the invoice table is started with {#IT} in the first column and ended with {/IT} in the last column. Columns in the rows can have String fields. In our example, {Item_description} and {Amount} Image: eDocGen offers to add images dynamically to the template. Follow the steps below. Upload the image to the eDogGen that should respond with an image_id. {%image_id} is the tag for populating images. The image will be fetched by image_id from eDocGen storage and replaced in the place of {%image_id}. The image_id is expected to be present in the input data. Conditional-based Dynamic fields (If-Else): Displaying content conditionally can be done with the Conditional tags. For example, When the language is English, {#language == "english"} English content will be displayed in the document. Likewise, multiple languages can be supported in a single document template. Mathematical calculations: eDocGen supports mathematical calculations based on formulae defined in the template. The summation of the amount of the items in the invoice can be calculated using the below formulae. JSON { IT // array of items | summation:'Amount' // value that needs to be used for calculation | format_number: ",” // format of the value } Please head over to JSON-to-pdf for more details. Template Upload Once the template is prepared, this can be uploaded for consumption. There are two ways. eDocGen's interactive UI - which has integration with dropbox, drive, Evernote eDocGen's RestAPI - which can be integrated into the client code for uploading templates. For the demo, purpose I have used the UI for uploading the template. On the successful upload, we get an ID as a response. This is the ID that will be used for generating the documents. Leaving here the Upload API structure for your reference, in case you wish to use API. JSON "/api/v1/document": { "post": { "tags": [ "Document" ], "description": "Upload template to eDocGen", "produces": [ "application/json" ], "consumes": [ "multipart/form-data" ], "parameters": [ { "name": "documentFile", "description": "file to upload", "required": true, "type": "file", "in": "formData" }, { "name": "x-access-token", "in": "header", "description": "JWT auth token from login", "required": true, "type": "string" } ], "responses": { "200": { "description": "Successfully uploaded document file" }, "other": { "description": "Operation failed" } } } } JSON to Document Generation Now we have our template ready. Let's generate the document. Document generation has two phases. .Request to generate the document .Download the document Step 1: Request To Generate the Document We request document generation with the details required and we get an acknowledgment. The process happens behind the screen asynchronously. Parameters Needed for the Document Generation API: POST - /api/v1/document/generate/bulk Request Body Form Data documentId id of the template format pdf/docx (Format should be supported by the template) outputFileName The file name for the output file. inputFile The file contains marker values. json, xlsx and xml supported. Header Content-Type multipart/form-data x-access-token JWT auth token from login Input Data The data in the inputFile should be in a structure defined by the template. For example, For the above template mapping will be like the below. Invoice_Number in JSON should be matching with {Invoice_Number} in the template. For table data, it should be an array of objects, with Item_Description and Amount. The amount should be a number for summation calculation. Step 2: Download the Document The generated document can be downloaded using the output ID obtained from the above step and the name of the output file. We will use two APIs here. API to know the file's existence : /api/v1/output/name/${fileName} API to download the file : /api/v1/output/download/${outputId} Since document generation happens asynchronously, to know whether the document is generated or not, we will use the /api/v1/output/name api. On the success response from API /api/v1/output/name will download the file. I have combined both of these steps in a single js file and it looks below. Java let login = require("../edocgen_login"); const fs = require("fs"); const uuid = require("uuid"); const FormData = require("form-data"); let axios = require("axios"); let fileName = uuid.v4(); const headers = { "Content-Type": "multipart/form-data", "x-access-token": "null", }; const hostName = "https://app.edocgen.com/api/v1/document/generate/bulk"; const outputFormat = "<format>";// pdf / docx const documentId = "<template_id>"; // id of the template we want to use module.exports.generateFiles = function () { let authToken = login.getToken(function handleUsersList(token) { headers["x-access-token"] = token; var formBody = new FormData(); formBody.append("documentId", documentId); formBody.append("format", outputFormat); formBody.append("outputFileName", fileName); // json data for the template formBody.append("inputFile", fs.createReadStream("./JSON_Data_Single.json")); // local path forjson file let config = { method: "post", url: hostName, headers: headers, data: formBody, }; console.log(`https://app.edocgen.com/api/v1/output/name/${fileName}.${outputFormat}`); let config_output = { method: "get", url:`https://app.edocgen.com/api/v1/output/name/${fileName}.${outputFormat}`, headers: headers, }; const MAX_RETRY = 50; let currentRetry = 0; // max retry for 50 times function errorHandler() { if (currentRetry < MAX_RETRY) { currentRetry++; console.log("Document is not prepared yet! Retrying..."); sendWithRetry(processResponse); } else { console.log("No luck. Document is not generated. Retried multiple times."); } } // sendWithRetry checks for file existence // on success, it proceeds to download the file // on failure, it retries // todo: introduce spin lock function sendWithRetry(callback) { axios(config_output) .then(function (response) { if (response.data.output.length !== 1) { throw new axios.Cancel("Document is not found. Throw error."); } else { callback(response); } }) .catch(errorHandler); } axios(config) .then(function (response) { sendWithRetry(processResponse); }) .catch(function (error) { console.log(error); }); }); }; function processResponse(response) { const outputId = response.data.output[0]._id; console.log( "Output Document is Generated. Id = ", response.data.output[0]._id ); let config_download = { method: "get", url: `https://app.edocgen.com/api/v1/output/download/${outputId}`, headers: headers, responseType: "arraybuffer", }; axios(config_download) .then(function (response) { console.log("Output file is downloaded " + `${fileName}.${outputFormat}`); fs.writeFileSync(`./${fileName}.${outputFormat}`, response.data); }) .catch(function (error) { console.log("Error while downloading"); console.log(error); }); } Single vs Multiple Documents When the data is single JSON, a single document of the given format will be generated. When the data is an array of objects, documents for each array element will be generated and zipped into a file. XML to Document Generation The procedure is simple for XML data. All we need to do is pass the XML file in the place of JSON data. Like JSON to document, For XML to Document as well, we need documentId, outputFileName, format and inputFile. Everything same as JSON, except the input file, will be an XML file. The sample XML data would look like below XML <?xml version="1.0" encoding="UTF-8" ?> <marker> <values> <Invoice_Number>SBU-2053501</Invoice_Number> <Invoice_Date>31-07-2020</Invoice_Date> <Terms_Payment>Net 15</Terms_Payment> <Company_Name>ABC company</Company_Name> <Billing_Contact>ABC-Contact1</Billing_Contact> <Address>New york, United State</Address> <Email>support@edocgen.com</Email> <Logo>621cd2b783a6095d7b15a443</Logo> <Sum1>6,751</Sum1> <para>61b334ee7c00363e11da3439</para> <ITH> <Heading1>Item Description</Heading1> <Heading2>Amount</Heading2> </ITH> <IT> <Item_Description>Product Fees: X</Item_Description> <Amount>5,000</Amount> </IT> </values> <marker> Code change that I made for XML as the data source is simple as below JavaScript var formBody = new FormData(); formBody.append("documentId", documentId); formBody.append("format", outputFormat); formBody.append("outputFileName", fileName); formBody.append("inputFile", fs.createReadStream("./XML_Invoice.xml")); Database to Document Generation Document generation from Databases is almost the same as other data sources. But in this case, instead of uploading the inputFile, we require to provide the connection details and SQL query. The output columns of the SQL query should be matching with the tags in the document template. Let's look at how to configure this in code. JavaScript const templateId = "<template id>"; const dbVendor = "mysql"; const dbUrl = "<jdbc connection URL>"; const dbLimit = "100"; const dbPassword = "<database password>"; const dbQuery = "SELECT JSON_ARRAY(first, last) FROM customers;"; const outputFormat = "pdf"; // form data prepareation let formBody = new FormData(); formBody.append("documentId", templateId); formBody.append("format", outputFormat); formBody.append("dbVendor", dbVendor); formBody.append("dbUrl", dbUrl); formBody.append("dbLimit", dbLimit); formBody.append("dbPassword", dbPassword); formBody.append("dbQuery", dbQuery); formBody.append("outputFileName", fileName); Everything else would remain the same. Sending the Document Over Email eDocGen provides the facility to send the generated document over Email. Parameters Needed for the Document Generation API: POST - /api/v1/output/email Request Body JSON outId Put output ID here which needs to be sent via email emailId Put user email here Header Content-Type multipart/form-data x-access-token JWT auth token from login Code Sample let login = require("../edocgen_login"); let axios = require("axios"); const hostName = "https://app.edocgen.com/api/v1/output/email"; const headers = { "Content-Type": "application/json", "x-access-token": "null", }; const outId = "<output ID>"; // Put output ID here which need to be sent via email const emailId = "<user email>"; // Put user email here module.exports.generateFiles = function () { let authToken = login.getToken(function handleUsersList(token) { headers["x-access-token"] = token; let payload = { outId: outId, emailId: emailId }; let config = { method: "post", url: hostName, headers: headers, data: payload, }; axios(config) .then(function (response) { console.log("Mail sent"); }) .catch(function (error) { console.log(error); }); }); }; The email from eDocGen would look like below: There are tons of other features that I couldn't cover here. But I hope this article could provide you with an idea of where to start. Will meet you with another exciting article. Have a good day!
Anthony Gore
Founder,
Vue.js Developers
John Vester
Lead Software Engineer,
Marqeta @JohnJVester
Justin Albano
Software Engineer,
IBM
Swizec Teller
CEO,
preona