Node.js Tutorial Table of content What is Node.js? Why Learn Node.js? How to Install Node.js? Applications of Node.js Example of Node.js Application Prerequisites to Learn Node.js Getting Started with Node.js Frequently Asked Questions on Node.js PDF Version Quick Guide Resources Job Search Discussion Node.js is a powerful JavaScript runtime environment, built on Google Chrome”s V8 JavaScript Engine. Node.js is open-source and cross platform. What is Node.js? Node.js is not a programming language like Python, Java or C/C++. Node.js is a runtime, similar to Java virtual machine, that converts JavaScript code into machine code. It is , widely used by thousands of developers around the world to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications. With Node.js, it is possible to use JavaScript as a backend. With JavaScript already being a popular choice for frontend development, application development around MERN (MongoDB, Express, React and Node.js.) and MEAN (MongoDB, Express, Angular and Node.js) stacks is being increasingly employed by developers. Why Learn Node.js? Node.js can be used to full fill multiple purpose like server-side programming, build APIs, etc. Node.js is used for server-side programming with JavaScript. Hence, you can use a single programming language (JavaScript) for both front-end and back-end development. Node.js implements asynchronous execution of tasks in a single thread with async and await technique. This makes Node.js application significantly faster than multi-threaded applications. Node.js is being used to build command line applications, web applications, real-time chat applications, REST APIs etc. How to Install Node.js? Different operating systems required different steps to install Node.js, please follow the provided methods according to your installed operating system. Node.js Installation on Windows Node.js Installation on Linux – Ubuntu Applications of Node.js Node.js is used for building different type of applications. Some of the application types are listed below. Streaming applications: Node.js can easily handle real-time data streams, where it is required to download resources on-demand without overloading the server or the user’s local machine. Node.js can also provide quick data synchronization between the server and the client, which improves user experience by minimizing delays using the Node.js event loop. Single page apps: Node.js is an excellent choice for SPAs because of its capability to efficiently handle asynchronous calls and heavy input/output(I/O) workloads. Data driven SPAs built with Express.js are fast, efficient and robust. Realtime applications: Node.js is ideal for building lightweight real-time applications, like messaging apps interfaces, chatbots etc. Node.js has an event- based architecture, as a result has an excellent WebSocket support. It facilitates real-time two-way communication between the server and the client. APIs: At the heart of Node.js is JavaScript. Hence, it becomes handling JSON data is easier. You can therefore build REST based APIs with Node.js. These are some of the use cases of Node.js. However, its usage is not restricted to these types. Companies are increasingly employing Node.js for variety of applications. Example of Node.js Application To create a basic Hello World application in Node.js, save the following single line JavaScript as hello.js file. console.log(“Hello World”); Open a powershell (or command prompt) terminal in the folder in which hello.js file is present, and enter the following command. The “Hello World” message is displayed in the terminal. PS D:nodejs> node hello.js Hello World To create a “Hello, World!” web application using Node.js, save the following code as hello.js: http = require(”node:http”); listener = function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/html response.writeHead(200, {”Content-Type”: ”text/html”}); // Send the response body as “Hello World” response.end(”<h2 style=”text-align: center;”>Hello World</h2>”); }; server = http.createServer(listener); server.listen(3000); // Console will print the message console.log(”Server running at http://127.0.0.1:3000/”); Run the above script from command line. C:nodejs> node hello.js Server running at http://127.0.0.1:3000/ The program starts the Node.js server on the localhost, and goes in the listen mode at port 3000. Now open a browser, and enter http://127.0.0.1:3000/ as the URL. The browser displays the Hello World message as desired. Prerequisites to Learn Node.js Before proceeding with this tutorial, you should have a basic understanding of JavaScript. As we are going to develop web-based applications using Node.js, it will be good if you have some understanding of other web technologies such as HTML, CSS, AJAX, etc. Getting Started with Node.js This tutorial is designed for software programmers who want to learn the Node.js and its architectural concepts from basics to advanced. This tutorial will give you enough understanding on all the necessary components of Node.js with suitable examples. Basics of Node.js Before going deep into nodejs you should familier with fundamentals of nodejs like environment setup, REPL terminal, NPM, Callbacks, Events, Objects, etc. Node.js Introduction Node.js Environment Setup Node.js First Application Node.js REPL Terminal Node.js Command Line Options Node.js Package Manager (NPM) Node.js Callbacks Concept Node.js Upload Files Node.js Send an Email Node.js Events Node.js Event Loop Node.js Event Emitter Node.js Debugger Node.js Global Objects Node.js Console Node.js Process Node.js File System Node.js Streams Node.js Scaling Application Node.js Packaging Node.js Modules Node.js modules provides a collection of functions that are used to perform different operations as per the requirements. All the improtant modules are listed below. Node.js Assert Module Node.js Buffer Module Node.js Console Module Node.js DNS Module Node.js OS Module Node.js Path Module Module Node.js Query String Tutorialspoint Node.js URL Tutorialspoint Node.js Utility Tutorialspoint Node.js V8 Tutorialspoint Node.js Jobs and Salary Node.js. is a popular tool for almost any kind of project. After Learning Node.js you can get job on different job profiles. Node.js Developer – Salary ranges in between ₹ 1.2 Lakhs to ₹ 12.6 Lakhs with an average annual salary of ₹ 5.7 Lakhs. Node.js Backend Developer – Salary ranges in between ₹ 1.2 Lakhs to ₹ 11.0 Lakhs with an average annual salary of ₹ 4.7 Lakhs. Frequently Asked Questions about Node.js Is Node.js Free to Use? Node.js is an open-source and cross-platform server framework. It is completely free to use on all the OS platforms – Windows, Linux, MacOS etc. Can Node.js
Category: Computer Programming
Node.js – NPM ”; Previous Next NPM − an acronym for Node Package Manager, refers to the Command line utility to install Node.js packages, perform version management and dependency management of Node.js packages. It also provides an online repository for node.js packages/modules which are searchable on https://www.npmjs.com/. A detailed documentation of NPM commands is also available on this link. If you are working with newer versions of Node.js (version 0.6.0 or later), the NPM utility is included with the Node.js binaries for all the OS platform bundles. Check the version of NPM in the command terminal − PS C:Usersmlath> npm -v 10.1.0 In case you have an older version of NPM, you need to update it to the latest version using the following command. npm install npm -g Note that YARN and PNPM tools are also available as alternatives for NPM. YARN installs packages more quickly and manage dependencies consistently across machines or in secure offline environments. PNPM (Performant NPM) is another fast and disk-space efficient package manager for Node.js packages. If your Node.js application depends on one or more external packages, they must be installed from NPM repository. NPM packages are installed in two modes either local or global. By default, a package is installed locally. Install Package Locally There is a simple syntax to install any Node.js module − npm install <Module Name> For example, following is the command to install a famous Node.js web framework module called express − npm install express Now you can use this module in your js file as following − var express = require(”express”); The local mode installation of a package refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require() method. Use –save at the end of the install command to add dependency entry into package.json of your application. The package.json file is a JSON file that is used to manage dependencies in Node.js projects. It contains information about the project, such as its name, version, and dependencies. The package.json file is used by the npm package manager to install and manage dependencies. The package.json file is typically located in the root directory of a Node.js project. It can be created by running the npm init command. Create a new folder for a new Node.js project, and run pnm init command inside it − PS D:nodejsnewnodeapp> npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (newnodeapp) newnodeapp version: (1.0.0) description: Test Node.js App entry point: (index.js) test command: git repository: keywords: test, nodejs author: mvl license: (ISC) About to write to D:nodejsNewNodeApppackage.json − { “name”: “newnodeapp”, “version”: “1.0.0”, “description”: “Test Node.js App”, “main”: “index.js”, “scripts”: { “test”: “echo “Error: no test specified” && exit 1″ }, “keywords”: [ “test”, “nodejs” ], “author”: “mvl”, “license”: “ISC” } Now, if we install express package into this package locally in this project, use the following command, it also adds dependency entry into the package.json. D:nodejsnewnodeapp>npm install express –save The package.json file in this folder will be updated to − { “name”: “newnodeapp”, “version”: “1.0.0”, “description”: “Test Node.js App”, “main”: “index.js”, “scripts”: { “test”: “echo “Error: no test specified” && exit 1″ }, “keywords”: [ “test”, “nodejs” ], “author”: “mvl”, “license”: “ISC”, “dependencies”: { “express”: “^4.18.2″ } } The express package code will be placed inside the node_modules subfolder of the package folder. If you have already placed all the project dependencies in your package.json file, all of them will be installed at once by simply running npm install (without any package name in front of it) You can also use -save-dev flag in the npm install command to add the package as DevDepndency. –save-dev installs and adds the entry to the package.json file devDependencies –no-save installs but does not add the entry to the package.json file dependencies –save-optional installs and adds the entry to the package.json file optionalDependencies –no-optional will prevent optional dependencies from being installed Shorthands of the flags can also be used − -S: –save -D: –save-dev -O: –save-optional The difference between devDependencies and dependencies is that the former contains development tools, like a testing library, while the latter is bundled with the app in production. Install Package Globally Globally installed packages/dependencies are stored in system directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but cannot be imported using require() in Node application directly. Now let”s try installing the express module using global installation. npm install express -g This will produce a similar result but the module will be installed globally. On Linux, the global packages are placed in /usr/lib/node_modules folder, while for Windows, the path is C:Usersyour-usernameAppDataRoamingnpmnode_modules. Update Package To update the package installed locally in your Node.js project, open the command prompt or terminal in your project project folder and write the following update command. npm update <package name> The following command will update the existing ExpressJS module to the latest version. PS D:nodejsnewnodeapp> npm update express up to date, audited 63 packages in 2s 11 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Uninstall Packages To uninstall a package from your project”s dependencies, use the following command to remove a local package from your project. npm uninstall <package name> The following command will uninstall ExpressJS from the application. PS D:nodejsnewnodeapp> npm uninstall express removed 62 packages, and audited 1 package in 603ms found 0 vulnerabilities The package entry will also be removed from the list of dependencies in the package.json file. Print Page Previous Next Advertisements ”;
Node.js – Introduction
Node.js – Introduction ”; Previous Next What is Node.js? Node.js is a server-side runtime environment built on Google Chrome”s JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v20.9.0. Node.js is a cross-platform (run on Windows, Linux, Unix, macOS, and more), open-source, back-end JavaScript runtime environment, that executes JavaScript code outside a web browser. The definition of Node.js as supplied by its official documentation is as follows − Node.js is a platform built on Chrome”s JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node.js environment is event-driven and provides non-blocking I/O, that optimizes throughput and scalability in web applications. The OpenJS Foundation, facilitated by the Linux Foundation”s Collaborative Projects program, now handles the Node.js distributed development. Features of Node.js Following are some of the important features that make Node.js the first choice of software architects. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Very Fast − Being built on Google Chrome”s V8 JavaScript Engine, Node.js library is very fast in code execution. Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server. No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks. License − Node.js is released under the MIT license. The following diagram depicts some important parts of Node.js which we will discuss in detail in the subsequent chapters. Where to Use Node.js? Following are the areas where Node.js is proving itself as a perfect technology partner. I/O bound Applications Data Streaming Applications Data Intensive Real-time Applications (DIRT) JSON APIs based Applications Single Page Applications However, it is not advisable to use Node.js for CPU intensive applications. Node.js is primarily used to build network programs such as Web servers. However, you can build different types of applications such as command line applications, web applications, real-time chat applications, REST APIs etc. Thousands of open-source libraries for Node.js are available, most of them hosted on the npm website, npm is a package manager for the JavaScript programming language. A number web frameworks can be used to accelerate the development of applications. Some of the popular frameworks are Express.js, Feathers.js, Koa.js, Sails.js, Meteor, and many others. Number of IDEs such as Atom, JetBrains WebStorm, NetBeans, and Visual Studio Code support development of Node.js applications. Cloud-hosting platforms like Google Cloud Platform and AWS Elastic Beanstalk can be used to host Node.js applications. Print Page Previous Next Advertisements ”;
Node.js – Command Line Options ”; Previous Next Any JavaScript file (with .js extension) can be executed from the command prompt, using it as a command line option to the node executable. PS D:nodejs> node hello.js You can invoke the Node.js REPL by running node without any option. PS D:nodejs> node > In addition, there are many options that can be used in the node command line. To get the available command line options, use –help PS D:nodejs> node –help Some of the frequently used command line options (sometimes also called switches) are as follows − Display version PS D:nodejs> node -v v20.9.0 PS D:nodejs> node –version v20.9.0 Evaluate script PS D:nodejs> node –eval “console.log(123)” 123 PS D:nodejs> node -e “console.log(123)” 123 Show help PS D:nodejs> node -h PS D:nodejs> node –help Start REPL PS D:nodejs> node -i PS D:nodejs> node –interactive Load module PS D:nodejs> node -r “http” PS D:nodejs> node –require “http” You can pass arguments to the script to be executed from the command line. The arguments are stored in a an array process.argv. The 0th element in the array is the nide executable, first element is the javascript file, followed by the arguments passed. Save the following script as hello.js and run it from command line, pass a string argument to it from command line. const args = process.argv; console.log(args); const name = args[2]; console.log(“Hello,”, name); In the terminal, enter PS D:nodejs> node hello.js TutorialsPoint [ ”C:\nodejs\node.exe”, ”D:\nodejs\a.js”, ”TutorialsPoint” ] Hello, TutorialsPoint You can also accept input from the command line in Node.js. Node.js since version 7 provides the readline module for this purpose. The createInterface() method helps in setting input from a readable stream such as the process.stdin stream, which during the execution of a Node.js program is the terminal input, one line at a time. Save the following code as hello.js const readline = require(”readline”).createInterface({ input: process.stdin, output: process.stdout, }); readline.question(`What”s your name?`, name => { console.log(`Hi ${name}!`); readline.close(); }); The question() method shows the first parameter (a question) and waits for the user input. It calls the callback function once enter is pressed. Run from command line. Node runtime waits for user input and then echoes the output on the console. PS D:nodejs> node a.js What”s your name?TutorialsPoint Hi TutorialsPoint! You can also set environment variables from the command line. Assign the values to one or more variables before the node executable name. USER_ID=101 USER_NAME=admin node app.js Inside the script, the environment variables are available as the properties of the process.env object. process.env.USER_ID; // “101” process.env.USER_NAME; // “admin” Print Page Previous Next Advertisements ”;
MATLAB Simulink – Quick Guide ”; Previous Next MATLAB Simulink – Introduction Simulink is a simulation and model-based design environment for dynamic and embedded systems, which are integrated with MATLAB. Simulink was developed by a computer software company MathWorks. It is a data flow graphical programming language tool for modelling, simulating and analysing multi-domain dynamic systems. It is basically a graphical block diagramming tool with a customisable set of block libraries. Furthermore, it allows you to incorporate MATLAB algorithms into models as well as export the simulation results into MATLAB for further analysis. Simulink supports the following − System-level design. Simulation. Automatic code generation. Testing and verification of embedded systems. To get started with Simulink, type simulink in the command window as shown below − It will open the Simulink page as shown below − You can also make use of Simulink icon present in MATLAB to get started with Simulink − When you start Simulink, you are navigated to the start page as shown below Here you can create your own model, and also make use of the existing templates. Click on the Blank Model and you will get a Simulink library browser that can be used to create your own model. The screen for Blank model is as follows − Click on Library and it will display you the Simulink library as shown below − The Simulink library browsers is a collection of many libraries. It offers Commonly Used Blocks, Continuous, Dashboard, Logic and Bit Operation, Math Operations etc. Besides that, you will get other library list like Control system toolbox, DSP system toolbox etc. Here is an example of Math operations library list − It has Abs, Add, Algebraic Constraint, Assignment etc. that you can make use in your model. Given below is an example of Logic and Bit Operations − MATLAB Simulink – Environment Setup MATLAB simulink is a MATLAB product and to work with it, we need to download MATLAB. The official website of matlab is https://www.mathworks.com/ The following page will appear on your screen − To download MATLAB go to https://in.mathworks.com/downloads/ as shown below. MATLAB is not free to download and you need to pay for the licensed copy. Later on you can download it. A free trial version is available for which you have to create a login for your respective account. Once an account is created, they allow you to download MATLAB and also an online version for a trial of 30 days’ license. Once you are done with the creating a login from their website, download MATLAB and install on your system. Then, start MATLAB or you can also make use of their online version. Simulink comes in-built with MATLAB. Once you install MATLAB, you will get Simulink as shown below − MATLAB Simulink – Starting Simulink In this chapter, we will understand about using Simulink to build models. Here is a MATLAB display − You can start Simulink by using simulink command in the MATLAB command window as shown below − Click on enter to open the Simulink startup page as shown below − You can also open Simulink from MATLAB interface directly by clicking on Simulink icon as shown below − When you click on the Simulink icon, it will take you to a Simulink startup page, as shown below − The startup page has a blank model, subsystem, library to start the model from scratch. There are also some built-in templates that can help the users to start with. To create a model, the user can click on blank model and it will display a page as shown below − Click on Save to save your model. The blocks to build your model are available inside the Simulink library browser. Click on library browser as shown below − The library browser has a list of all types of libraries with different blocks as shown below − Libraries in Simulink Let us understand some of the commonly used libraries in Simulink. Continuous A continuous blocks library gives you blocks related to derivatives and integrations. The list of blocks are as follows − Dashboard With Dashboard, you will get controls and indicator blocks that help to interact with simulations. The following screen will appear on your computer − Discontinuities Here, you will get a list of discontinuous functions blocks as displayed below − Discrete Here, you will get time relation function blocks as shown below − Logic and Bit Operations In this category, you will get all logical and relational type blocks as displayed below − Lookup Tables You will all the sine, cosine function blocks as shown below − Math Operations All mathematical operations like Add, Absolute, divide, subtract are available. The list is as follows − Messages and Events This block has all the message/communication related functions as shown below − Model Verification The blocks present here helps to self-verify models, such as Check Input Resolution. The following screen will appear on your computer − Model-Wide Utilities This gives you blocks like Model info, Block Support Table etc. The following screen will appear on your computer − Ports and Subsystems You will get blocks like a subsystem, switch case, enable etc. The list is displayed below − Signal Attributes Modify the signal attribute blocks such as Data Type Conversion. The following screen will appear on your computer −
Solving Mathematical Equation ”; Previous Next In this chapter, we will solve a simple mathematical equation by using Simulink. The equation is given below − y(t) = 2Sin(t) + 5Sin(2t) – 10 Let us create a model for the above equation. Open a blank model as shown below − Following are the steps to solve the equation − Get a Sine wave block. Right click and select block parameters. Select sign type as time based. Change the amplitude to 2 and frequency to 1. That will be 2Sin(t). Get another sine wave block. Now, set the amplitude to 5 and frequency to 2 to display 5Sin(2t). Select sign type as time based. Now get an add block and add both sine waves. Get a constant. Right click and select block parameters. Change the value from 1 to 10. Get a subtract block where one input will come from step 3 and another from constant i.e. step 4. Get a scope block and connect the input from step 6 to it. This is how the final Simulink model looks like for the equation − y(t) = 2Sin(t) + 5Sin(2t) – 10 Click on the run button to compile. Right Click on scope block to see the signal plotted. Print Page Previous Next Advertisements ”;
MATLAB Simulink – Sinewave
MATLAB Simulink – Sine Wave ”; Previous Next In this chapter we will integrate and differentiate sine wave by using the derivative and integrator blocks. Open blank model and Simulink library as shown below − Let us pick the sine wave from sources library and scope block from sinks library. We would like to add the derivative and integrator block from continuous library as shown below − We would need 3 input ports for scope block as the sine wave, derivative and integrator block will be connected to it. Right click on the scope block and change the inputs from 1 to 3 as shown below − Connect the lines as shown below − Now, run the model to see the display. So, we have three signals sine wave, derivative and integrator. Print Page Previous Next Advertisements ”;
MATLAB Simulink – Discussion
Discuss MATLAB Simulink ”; Previous Next MATLAB (Matrix Laboratory) is a programming language developed by a computer software company MathWorks. Simulink is a simulation and model-based design environment for dynamic and embedded systems, which are integrated with MATLAB. Simulink is also developed by MathWorks. This tutorial is designed to give students fluency in MATLAB Simulink. Problem-based examples have also been given in simple and easy way to make your learning fast and effective. Print Page Previous Next Advertisements ”;
First Order Differential Equation ”; Previous Next Here, we will learn how to solve the first order differential equation in Simulink. The first order differential equation that we are trying to solve using Simulink is as follows − dy/dt = 4sin2t – 10y The equation can be solved by integrating dy/dt to the following − y(t)=∫(4sin2t – 10y(t))dt Following are the steps to build a model for above equation. Pick up sine wave from sources library and change the amplitude to 4 and frequency to 2. This will give us 4sin2t. The integrator block will be used to show dy/dt that will give output y(t). The gain block will represent 10y. The input of step 1 and 3 will be given to step2. We need scope block to see the output y(t). The step 4 will be connected to the scope block. Let us see the above steps in model as shown below − Run the block to see the following output − Print Page Previous Next Advertisements ”;
MATLAB Simulink – Create Subsystem ”; Previous Next Subsystems are useful when your model gets big and complex. You can change a part of the model into a subsystem that helps to keep the flow very clean and understandable. In this chapter, let us learn how to create a simple subsystem in Simulink. First, create a blank model, as shown below − Now, we will create a simple model that adds two numbers and later converts a part of the model into a subsystem. We have created a simple model that has two inputs. These inputs will add up and show the result inside the display. We will change the value of the constant as 10 and 20. The result 10+20 = 30 should be seen inside the display block. Let us add one more block named Unary minus that will change the output from 30 to -30 as shown below − Now, let us select the portion i.e. the sum and the Unary minus block to create a subsystem as shown below − Click on Create Subsystem. Once done, the sum block and the Unary minus block will be converted into a subsystem as shown below − Now when you run the simulation, it will display the same result as earlier Double click on the subsystem to see the original block as shown below − Click on the upward arrow close to the subsystem to get back to the model. Print Page Previous Next Advertisements ”;