Node.js – File System

Node.js – File System ”; Previous Next The Node.js API is a server-side programming technology. Hence, a Node.js application may be required to interact with the physical file system of the server. The Node.js API includes fs module that enables the developer to perform read/write operations on disk files. The fs module in Node.js provides synchronous as well as asynchronous methods for file handling. To use the filesystem functions, you need to import the fs module using the following syntax − var fs = require(“fs”) Synchronous vs Asynchronous Every method in the fs module has synchronous as well as asynchronous version. Asynchronous methods take the last parameter as the completion function callback and the first parameter of the callback function as error. For example, the synchronous method for writing data in a file is − fs.writeFileSync(file, data[, options]) On the other hand, its asynchronous version has the following syntax − fs.writeFile(file, data[, options], callback) The asynchronous methods are non-blocking in nature as compared to the synchronous methods. For the example codes in this chapter, we shall use a text file named input.txt with the following content − Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Writing a file The following program shows how to write data in a file with synchronous as well as asynchronous methods. const fs = require(”fs”); var text = `Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! `; console.log(“Writing synchronously”); fs.writeFileSync(“input.txt”, text); console.log(“Writing asynchronously”); fs.writeFile(”input.txt”, text, function (err) { if (err) console.log(err); else console.log(”Write operation complete.”); }); Output Writing synchronously Writing asynchronously Write operation complete. Reading a file The ReadFile() method in fs module reads a file asynchronously. It has the following syntax − fs.readFile(fileName [,options], callback) On the other hand, the ReadFileSync() method is its synchronous version, with the following syntax − fs.readFileSync(fileName [,options]) Example The following program reads the input.txt file synchronously as well as asynchronously. const fs = require(”fs”); console.log(“Reading synchronously”); data = fs.readFileSync(“input.txt”); console.log(data.toString()); console.log(“Reading asynchronously”); fs.readFile(”input.txt”, function (err, data) { if (err) { return console.error(err); } console.log(“Asynchronous read: ” + data.toString()); }); console.log(”Read operation complete.”); Output Reading synchronously Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Reading asynchronously Read operation complete. Asynchronous read: Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Open a file The readFile() and writeFile() method open and close the file to be read/written implicitly. Instead, you can explicitly open a file, set the file opening mode indicating whether to use it for reading or writing, and then close the file. The open() method has the following signature − fs.open(path, flags[, mode], callback) Parameters path − This is the string having file name including path. flags − Flags indicate the behavior of the file to be opened. All possible values have been mentioned below. mode − It sets the file mode (permission and sticky bits), but only if the file was created. It defaults to 0666, readable and writeable. callback − This is the callback function which gets two arguments (err, fd). The values of flag parameter are − Sr.No. Flag & Description 1 r Open file for reading. An exception occurs if the file does not exist. 2 r+ Open file for reading and writing. An exception occurs if the file does not exist. 3 rs Open file for reading in synchronous mode. 4 rs+ Open file for reading and writing, asking the OS to open it synchronously. See notes for ”rs” about using this with caution. 5 w Open file for writing. The file is created (if it does not exist) or truncated (if it exists). 6 wx Like ”w” but fails if the path exists. 7 w+ Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). 8 wx+ Like ”w+” but fails if path exists. 9 a Open file for appending. The file is created if it does not exist. 10 ax Like ”a” but fails if the path exists. 11 a+ Open file for reading and appending. The file is created if it does not exist. 12 ax+ Like ”a+” but fails if the the path exists. Let us open a file “input.txt” for writing data into it. const fd = fs.open(”input.txt”, ”w”, (err, fd) => { if (err) { console.log(err); return; } }); To open() method returns a reference to the file, called as File Descriptor. A file descriptor is a unique integer, and used as an argument for the methods performing write and read operations. The write() method in fs module saves data into the file referred to by the file descriptor that the open() method returns. write(fd, string[, position[, encoding]], callback) Parameters fd − The file descriptor string − the data to be written position − to start writing from Default: null encoding − character encoding string Default: ”utf8” callback − The callback function to be invoked. Following snippet writes the given text into the file we have opened above. var data = `Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! `; if (err) { console.log(err); return; } It is always recommended to close the opened file, especially if opened in writable mode. // Close the file fs.close(fd, (err) => { if (err) { console.log(err); return; } }); Let us put all these snippets together as a program to open a file in writable mode, put some data in it, and close it. Example const fs = require(”fs”); // Open a file for writing const fd = fs.open(”input.txt”, ”w”, (err, fd) => { if (err) { console.log(err); return; } // Write some data to the file var data = `Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! `; fs.write(fd, data, (err) => { if (err) { console.log(err); return;

Node.js – MySQL Join

Node.js – MySQL Join ”; Previous Next In this chapter, you will learn how we can implement the JOIN query in a Node.js application on the tables in a MySQL database. A relational database consists of multiple related tables linking together using common columns, which are known as foreign key columns. MySQL supports JOIN query with which it is possible to extract and use data from more than one tables in a Node.js application. As in the earlier examples, we should call the mysql.query() method, and pass a SQL query string to mysql.query() method, the string should represent the MySQL JOIN query syntax. We shall use the following tables in this chapter − Members table CREATE TABLE members ( member_id INT AUTO_INCREMENT, name VARCHAR(100), PRIMARY KEY (member_id) ); INSERT INTO members(name) VALUES(”John”),(”Jane”),(”Mary”),(”David”),(”Amelia”); Data in members table − mysql> select * from members; +———–+——–+ | member_id | name | +———–+——–+ | 1 | John | | 2 | Jane | | 3 | Mary | | 4 | David | | 5 | Amelia | +———–+——–+ Committees table CREATE TABLE committees ( committee_id INT AUTO_INCREMENT, name VARCHAR(100), PRIMARY KEY (committee_id) ); INSERT INTO committees(name) VALUES(”John”),(”Mary”),(”Amelia”),(”Joe”); Data in Committees table − mysql> select * from committees; +————–+——–+ | committee_id | name | +————–+——–+ | 1 | John | | 2 | Mary | | 3 | Amelia | | 4 | Joe | +————–+——–+ Some members are committee members, and some are not. On the other hand, some committee members are in the members table, some are not. MySQL INNER JOIN The syntax of using the inner join clause in the SELECT statement is as follows − SELECT column_list FROM table_1 INNER JOIN table_2 ON join_condition; The inner join clause compares each row from the first table with every row from the second table. If values from both rows satisfy the join condition, a new row created in the resuleset whose column contains all columns of the two rows from both tables and includes this new row in the result set. In other words, the inner join clause includes only matching rows from both tables. If the join condition uses the equality operator (=) with the matching column name being same in both the tables, you can use the USING clause instead of ON clause. SELECT column_list FROM table_1 INNER JOIN table_2 USING (column_name); Example In the following Node.js code, we shall use the members and Committees tables and obtain their Inner Join. var mysql = require(”mysql”); var con = mysql.createConnection({ host: “localhost”, user: “root”, password: “mypassword”, database: “mydb” }); var qry =` SELECT m.member_id, m.name AS member, c.committee_id, c.name AS committee FROM members m INNER JOIN committees c ON c.name = m.name; `; con.connect(function (err) { if (err) throw err; console.log(“Connected!”); con.query(qry, function (err, results) { if (err) throw err; results.forEach((row) => { console.log(JSON.stringify(row)); }); }); con.end(); }); Output {“member_id”:1,”member”:”John”,”committee_id”:1,”committee”:”John”} {“member_id”:3,”member”:”Mary”,”committee_id”:2,”committee”:”Mary”} {“member_id”:5,”member”:”Amelia”,”committee_id”:3,”committee”:”Amelia”} MySQL LEFT JOIN Left join is similar to an inner join. When joining two tables using a left join, the left join selects data starting from the left table. For each row in the left table, the left join compares with every row in the right table. If the values in the two rows satisfy the join condition, the left join clause creates a new row whose columns contain all columns of the rows in both tables and includes this row in the result set. If the values in the two rows are not matched, the left join clause still creates a new row whose columns contain columns of the row in the left table and NULL for columns of the row in the right table. Hence, the left join selects all data from the left table whether there are matching rows exist in the right table or not. In case there are no matching rows from the right table found, the left join uses NULLs for columns of the row from the right table in the result set. The syntax of a left join clause is as follows − SELECT column_list FROM table_1 LEFT JOIN table_2 USING (column_name); Let us change the query string in out Node.js code to the following statement − Example var qry =` SELECT m.member_id, m.name AS member, c.committee_id, c.name AS committee FROM members m LEFT JOIN committees c USING(name); `; Output {“member_id”:1,”member”:”John”,”committee_id”:1,”committee”:”John”} {“member_id”:2,”member”:”Jane”,”committee_id”:null,”committee”:null} {“member_id”:3,”member”:”Mary”,”committee_id”:2,”committee”:”Mary”} {“member_id”:4,”member”:”David”,”committee_id”:null,”committee”:null} {“member_id”:5,”member”:”Amelia”,”committee_id”:3,”committee”:”Amelia”} The unmatched columns are filled with NULL data. To find members who are not the committee members, you add a WHERE clause and IS NULL operator. SELECT m.member_id, m.name AS member, c.committee_id, c.name AS committee FROM members m LEFT JOIN committees c USING(name) WHERE c.committee_id IS NULL; MySQL RIGHT JOIN The right join clause is similar to the left join clause except that the treatment of left and right tables is reversed. The right join starts selecting data from the right table instead of the left table. The right join clause selects all rows from the right table and matches rows in the left table. If a row from the right table does not have matching rows from the left table, the column of the left table will have NULL in the final result set. SELECT column_list FROM table_1 RIGHT JOIN table_2 USING (column_name); Let us modify the query string variable as follows − var qry =` SELECT m.member_id, m.name AS member, c.committee_id, c.name AS committee FROM members m RIGHT JOIN committees c on c.name = m.name; `; The result returns the RIGHT JOIN of two tables

Node.js – Event Emitter

Node.js – Event Emitter ”; Previous Next The Node.js API is based on an event-driven architecture. It includes the events module, which provides the capability to create and handle custom events. The event module contains EventEmitter class. The EventEmitter object emits named events. Such events call the listener functions. The Event Emitters have a very crucial role the Node.js ecosystem. Many objects in a Node emit events, for example, a net.Server object emits an event each time a peer connects to it, or a connection is closed. The fs.readStream object emits an event when the file is opened, closed, a read/write operation is performed. All objects which emit events are the instances of events.EventEmitter. Since the EvenEmitter class is defined in events module, we must include in the code with require statement. var events = require(”events”); To emit an event, we should declare an object of EventEmitter class. var eventEmitter = new events.EventEmitter(); When an EventEmitter instance faces any error, it emits an ”error” event. When a new listener is added, ”newListener” event is fired and when a listener is removed, ”removeListener” event is fired. Sr.No. Events & Description 1 newListener(event, listener) event − String: the event name listener − Function: the event handler function This event is emitted any time a listener is added. When this event is triggered, the listener may not yet have been added to the array of listeners for the event. 2 removeListener(event, listener) event − String The event name listener − Function The event handler function This event is emitted any time someone removes a listener. When this event is triggered, the listener may not yet have been removed from the array of listeners for the event. Following instance methods are defined in EventEmitter class − Sr.No. Events & Description 1 addListener(event, listener) Adds a listener at the end of the listeners array for the specified event. Returns emitter, so calls can be chained. 2 on(event, listener) Adds a listener at the end of the listeners array for the specified event. Same as addListener. 3 once(event, listener) Adds a one time listener to the event. This listener is invoked only the next time the event is fired, after which it is removed 4 removeListener(event, listener) Removes a listener from the listener array for the specified event. If any single listener has been added multiple times to the listener array for the specified event, then removeListener must be called multiple times to remove each instance. 5 removeAllListeners([event]) Removes all listeners, or those of the specified event. It”s not a good idea to remove listeners that were added elsewhere in the code, especially when it”s on an emitter that you didn”t create (e.g. sockets or file streams). 6 setMaxListeners(n) By default, EventEmitters will print a warning if more than 10 listeners are added for a particular event. Set to zero for unlimited. 7 listeners(event) Returns an array of listeners for the specified event. 8 emit(event, [arg1], [arg2], […]) Execute each of the listeners in order with the supplied arguments. Returns true if the event had listeners, false otherwise. 9 off(event, listener) Alias for removeListener Example Let us define two listener functions as below − var events = require(”events”); var eventEmitter = new events.EventEmitter(); // listener #1 var listner1 = function listner1() { console.log(”listner1 executed.”); } // listener #2 var listner2 = function listner2() { console.log(”listner2 executed.”); } Let us bind these listeners to a connection event. The first function listener1 is registered with addListener() method, while we use on() method to bind listener2. // Bind the connection event with the listner1 function eventEmitter.addListener(”connection”, listner1); // Bind the connection event with the listner2 function eventEmitter.on(”connection”, listner2); // Fire the connection event eventEmitter.emit(”connection”); When the connection event is fired with emit() method, the console shows the log message in the listeners as above listner1 executed. listner2 executed. Let us remove the listener2 callback from the connection event, and fire the connection event again. // Remove the binding of listner1 function eventEmitter.removeListener(”connection”, listner1); console.log(“Listner1 will not listen now.”); // Fire the connection event eventEmitter.emit(”connection”); The console now shows the following log − listner1 executed. listner2 executed. Listner1 will not listen now. listner2 executed. The EventEmitter class also has a listCount() method. It is a class method, that returns the number of listeners for a given event. const events = require(”events”); const myEmitter = new events.EventEmitter(); // listener #1 var listner1 = function listner1() { console.log(”listner1 executed.”); } // listener #2 var listner2 = function listner2() { console.log(”listner2 executed.”); } // Bind the connection event with the listner1 function myEmitter.addListener(”connection”, listner1); // Bind the connection event with the listner2 function myEmitter.on(”connection”, listner2); // Fire the connection event myEmitter.emit(”connection”); console.log(“Number of Listeners:” + myEmitter.listenerCount(”connection”)); Output listner1 executed. listner2 executed. Number of Listeners:2 Print Page Previous Next Advertisements ”;

Node.js – MySQL Create Database

Node.js – MySQL Create Database ”; Previous Next One or more databases (or schemas) can be created on a MySQL server. While we can create databases with MySQL query CREATE DATABASE, as well as with Workbench, we are interested in creating a database with a Node.js program. Databases are where we store our data in the form of tables. We use the MySQL query CREATE DATABASE to create a database. Syntax Following is the syntax of the MySQL Creating Database query − CREATE DATABASE IF NOT EXISTS database_name; Example Create a database of your choice, in here we are creating one for a pet store and hence calling it mydb and, running the command “CREATE DATABASE” on MySQL Command Line Client. mysql> CREATE DATABASE IF NOT EXISTS mydb; Query OK, 1 row affected (0.02 sec) To verify database creation, we can run the “SHOW DATABASES” query − mysql> show databases; +——————–+ | Database | +——————–+ | information_schema | | mydb | | mysql | | performance_schema | | sakila | | sys | | world | +——————–+ 7 rows in set (0.00 sec) con.query() method The connection object returned by mysql.createConnection() method has access to a query() method. A string representation of any valid MySQL query is passed to it as an argument. The second argument to query() method is a callback function. The query() method is used as follows − con.query(sql, function (err, result) {. . . . . . }); We just need to change the “sql” argument in the query() function with the desired query in the string format. Since the query to create a database in MySQL is “CREATE DATABASE $database_name$”, then, the syntax to create a database using the Node.js con.query() function becomes − con.query(“CREATE DATABASE $database_name$;”, function (err, result) { //Your code }); Example Following the Java Script example is trying to create a MySQL database named mydb. To do so − First of all, you need to replace the “sql” argument in the query function with “CREATE DATABASE mydb;” and run the file using node. Now, to check if you”ve created the database, we can use the MySQL query “SHOW DATABASES;”. For this, you need to execute the con.query() function again this time you need to pass the “SHOW DATABASES;” query as the first parameter. The SHOW DATABASES query returns an array of RowDataPacket objects. You need to stringify each object in the array to get the database name. Run a loop to look at all the databases with their names and find the database you”ve just created. We have added the IF NOT EXISTS clause while creating the database as we don”t want any error to occur during the creation of the database in case it has already been created. var mysql = require(”mysql”); var con = mysql.createConnection({ host: “localhost”, user: “root”, password: “mypassword” }); con.connect(function (err) { if (err) throw err; console.log(“Connected!”); con.query(“CREATE DATABASE IF NOT EXISTS mydb;”, function (err, result) { if (err) throw err; console.log(“Created database successfully”); }); con.query(“SHOW DATABASES;”, function (err, result) { if (err) throw err; console.log(“Showing databasesn”); for (var i = 0; i < result.length; i++) { console.log(JSON.stringify(result[i])); } }) con.end(); }); Output Connected! Created database successfully Showing databases {“Database”:”information_schema”} {“Database”:”mydb”} {“Database”:”mysql”} {“Database”:”performance_schema”} {“Database”:”sakila”} {“Database”:”sys”} {“Database”:”world”} Print Page Previous Next Advertisements ”;

Node.js – Send an Email

Node.js – Send an Email ”; Previous Next Sending Email is one the desired features in any Node.js application, especially an Express app. There are various third party modules that facilitate this on the NPM repository. A Node.js app can be integrated with email facility with email APIs such as Mailgun, MailTrap, Mailjet etc. In this chapter, we shall learn how to send email with a Node.js application with the help of nodemailer module and MilTrap API. Nodemailer Nodemailer is a module that enables email sending for Node.js applications. You can send emails with plain text as well as HTML content. It also supports adding attachments, secured TLS delivery, built-in SMTP support, OAUTH2 authentication among many other features. To get started, install the nodemailer module. npm install nodemailer To test our email-enabled Node.js application, we shall use Mailtrap service, that provides a dummy SMTP server. You can use the real SMTP server URL when the application goes to the production stage. Create a Mailtrap account and obtain the API credentials from the Integrations dropdown on the dashboard, select Nodemailer. Save the above code along with the rest of the code given below − const nodemailer = require(”nodemailer”); var transport = nodemailer.createTransport({ host: “sandbox.smtp.mailtrap.io”, port: 2525, auth: { user: “f924c******a56”, pass: “******1b5516a0″ } }); message = { from: “[email protected]”, to: “[email protected]”, subject: “Subject”, text: “Hello SMTP Email” } transport.sendMail(message, function(err, info) { if (err) { console.log(err); } else { console.log(info); } }); Nodemailer”s createTransport function specifies which method you want to use for sending email. It takes the connection data and credentials as an argument. In this case, since SMTP is the preferred transport, you will need to define an SMTP host, port, and credential password for accessing a host SMTP server. The createTrsnsport() function returns a transport object. It”s sendMail() method uses the credentials and message details and sends the message to the desired recipient. Run the above code as follows − PS D:nodejsemailapp> node main.js { accepted: [ ”[email protected]” ], rejected: [], ehlo: [ ”SIZE 5242880”, ”PIPELINING”, ”ENHANCEDSTATUSCODES”, ”8BITMIME”, ”DSN”, ”AUTH PLAIN LOGIN CRAM-MD5” ], envelopeTime: 749, messageTime: 529, messageSize: 291, response: ”250 2.0.0 Ok: queued”, envelope: { from: ”[email protected]”, to: [ ”[email protected]” ] }, messageId: ”<[email protected]>” } The dummy SMTP server provided by MailTrap provides you an inbox, wherein the email transaction can be verified. You can also use the popular Gmail service to send email through your Node.js code. Note that you may have to either enable less secure apps setting of the gmail account or use the authentication token if the account is using OAuth2 authentication. var transport = nodemailer.createTransport({ service: ”gmail”, auth: { user: ”[email protected]”, pass: ”yourpassword” } }); Mailgun You can also incorporate email facility in your Node.js application by using Mailgun API keys. To add this facility, install following modules − npm i mailgun.js form-data Sign up for a free Mailgun account by visiting the URL signup.mailgun.com and obtain public and private API keys. Then, we initialize the Mailgun client instance and passing in the MAILGUN_API_KEY. Then we defined a function sendMail to handle the sending of emails using the mailgun-js library. const formData = require(“form-data”); const Mailgun = require(“mailgun.js”); const mailgun = new Mailgun(formData); const mg = mailgun.client({ username: “api”, key: process.env.MAILGUN_API_KEY, }); exports.sendMail = (req, res) => { const { toEmail, fromEmail, subject, message } = req.body; mg.messages.create(process.env.MAILGUN_DOMAIN, { from: fromEmail, to: [toEmail], subject: subject, text: message, }); }; Print Page Previous Next Advertisements ”;

Node.js – MongoDB Find

Node.js – MongoDB Find ”; Previous Next The MongoShell client is similar to the MySQL command-line tool. It is a tool for interaction with the MongoDB database. You can use MongoDB Language to perform CRUD operations. MongoDB Language is similar to SQL. The find() and findOne() methods available to the Collection object are the equivalent of SELECT query as in SQL. These methods are also defined in the mongodb module for use with Node.js application. The find() method has one argument in the form of a query in JSON format. db.collection.find({k:v}); The find() method returns a resultset consisting of all the documents from the collection that satisfy the given query. If the query argument is empty, it returns all the documents in the collection. Read all documents The following example retrieves all the documents in the products collection. Example const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/”; const client = new MongoClient(uri); try { // Connect to the MongoDB cluster await client.connect(); // Make the appropriate DB calls // Create a single new listing await listall(client, “mydb”, “products”); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function listall(client, dbname, colname){ const result = await client.db(“mydb”).collection(“products”).find({}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”65809214693bd4622484dce3″,”ProductID”:1,”Name”:”Laptop”,”Price”:25000},{“_id”:”6580964f20f979d2e9a72ae7″,”ProductID”:1,”Name”:”Laptop”,”price”:25000},{“_id”:”6580964f20f979d2e9a72ae8″,”ProductID”:2,”Name”:”TV”,”price”:40000},{“_id”:”6580964f20f979d2e9a72ae9″,”ProductID”:3,”Name”:”Router”,”price”:2000},{“_id”:”6580964f20f979d2e9a72aea”,”ProductID”:4,”Name”:”Scanner”,”price”:5000},{“_id”:”6580964f20f979d2e9a72aeb”,”ProductID”:5,”Name”:”Printer”,”price”:9000}] You can also traverse the resultset with a forEach loop as follows − var count=0; result.forEach(row => { count++; console.log(count, row[”Name”], row[”price”]); }); Output 1 Desktop 20000 2 Laptop 25000 3 TV 40000 4 Router 2000 5 Scanner 5000 6 Printer 9000 findOne() The findOne() method returns the first occurrence of the given query. The following code returns the document with name of the product as TV async function listall(client, dbname, colname){ const result = await client.db(dbname).collection(colname).find({“Name”:”TV”}).toArray(); console.log(JSON.stringify(result)); } Output [{“_id”:”6580964f20f979d2e9a72ae8″,”ProductID”:2,”Name”:”TV”,”price”:40000}] If the query is empty, it returns the first document in the collection. async function listall(client, dbname, colname){ const result = await client.db(dbname).collection(colname).findOne({}); console.log(JSON.stringify(result)); } Output {“_id”:”65809214693bd4622484dce3″,”ProductID”:1,”Name”:”Laptop”,”Price”:25000} Print Page Previous Next Advertisements ”;

Node.js – Dicussion

Discuss Node.js ”; Previous Next Node.js is a very powerful JavaScript-based framework/platform built on Google Chrome”s JavaScript V8 Engine. It is used to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications. Node.js is open source, completely free, and used by thousands of developers around the world. Print Page Previous Next Advertisements ”;

Node.js – Debugger

Node.js – Debugger ”; Previous Next For smaller Node.js code, you can use console.log() or console.debug() functions to intermittently display messages or values of variables to manually debug the code. However, if the Node.js code becomes bigger and more complex, the manual method is not helpful. Instead, we can use the inbuilt debugger in Node.js runtime. Consider a simple Node.js code as given below (main.js) − let marks = [34, 45, 98, 26, 51]; let total = 0; for (let i = 0; i <= marks.length; i++) { total += marks[i]; } var no = marks.length; console.log(total/no); We expect that the above program calculates the average marks obtained by 5 students. However, the result is not what we expect, when we run it as follows − PS D:nodejs> node main.js NaN In JavaScript, NaN means Not a Number. To trace this error, let’s use the Node.js debugger. Instead, run the program with the following command − PS D:nodejs> node inspect main.js < Debugger listening on ws://127.0.0.1:9229/ca4aece6-308a-4979-8a32-734fe8ebbd0b < For help, see: https://nodejs.org/en/docs/inspector < connecting to 127.0.0.1:9229 … ok < Debugger attached. < Break on start in a.js:1 > 1 let marks = [34, 45, 98, 26, 51]; 2 3 let total = 0; debug> The built-in debugger starts at port 9229 of the localhost. The debugger breaks at the first line in the code. We step through code by telling the debugger to go to the next line that the program will execute. Node.js allows the following commands to use a debugger − Sr.No Commands & Description 1 c or cont Continue execution to the next breakpoint or to the end of the program. 2 n or next Move to the next line of code. 3 s or step Step into a function. By default, we only step through code in the block or scope we’re debugging. 4 o Step out of a function. After stepping into a function, the debugger goes back to the main file when the function returns. 5 pause Pause the running code. Press ‘n’ or ‘next’ successively to traverse the code. In this loop, two variables are changed every iteration—total and i. Let’s set up watchers for both of those variables. debug> watch(”total”) debug> watch(”i”) When you press ‘n’ in front of debug prompt, you get to see the instantaneous values of the two variables under watch. break in main.js:6 Watchers: 0: total = 0 1: i = 0 4 5 > 6 for (let i = 0; i <= marks.length; i++) { 7 total += marks[i]; 8 } Every time you press next, the changing values or total and I are displayed in debugger. At the last iteration, the status of debugger is − Watchers: 0: total = 254 1: i = 5 4 5 > 6 for (let i = 0; i <= marks.length; i++) { 7 total += marks[i]; 8 } Next time, the value of total becomes NaN as the loop is trying to go beyond the array. Watchers: 0: total = NaN 1: i = 6 4 5 > 6 for (let i = 0; i <= marks.length; i++) { 7 total += marks[i]; 8 } Hence, we can come to know that the error is in the formation of for loop. The built-in debugger helps in identifying the error. You can also enable debugging Node.js code inside VS Code. Open the command palette by pressing ctrl+shift+p and choose Attach Node.JS process. Then start debugging the program from the Run menu. It allows you to Step Over, Step Into and Step Out operations in the code to trace the flow of the program. You can also set watches on one or more variables to keep track of the values while the program is being executed step by step. Print Page Previous Next Advertisements ”;

Node.js – Events

Node.js – Events ”; Previous Next When JavaScript is used inside HTML script, it generally handles the user-generated events such as button press or mouse clicks. The core API of Node.js is an asynchronous event-driven architecture. However, unlike the client-side JavaScript, it handles the events on the server, such as File io operations, server”s request and responses etc. The net.Server object emits an event each time a peer connects to it. The ReadStream referring to a file emits an event when the file is opened and whenever data is available to be read. Node.js identifies several types of events. Each event can be attached to a callback function. Whenever an event occurs, the callback attached to it is triggered. The Node.js runtime is always listening to events that may occur. When any event that it can identify occurs, its attached callback function is executed. The Node.js API includes events module, consisting mainly the EventEmitter class. An EventEmmiter object triggers (or emits) a certain type of event. You can assign one or more callbacks (listeners) to a certain type of event. whenever that event triggers, all the registered callbacks are fired one by one in order to which they were registered. These are the steps involved in event handling in Node.js API. First, import the events module, and declare an object of EventEmitter class // Import events module var events = require(”events”); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); Bind an event handler with an event with the following syntax − // Bind event and event handler as follows eventEmitter.on(”eventName”, eventHandler); To fire the event programmatically − // Fire an event eventEmitter.emit(”eventName”); Example Given below is a simple example that binds two listeners to the on event of EventEmitter class // Import events module var events = require(”events”); // Create an eventEmitter object var eventEmitter = new events.EventEmitter(); // Create an event handler as follows var connectHandler = function connected() { console.log(”connection successful.”); } // Bind the connection event with the handler eventEmitter.on(”connection”, connectHandler); // Bind the data_received event with the anonymous function eventEmitter.on(”data_received”, function(){ console.log(”data received successfully.”); }); // Fire the connection event eventEmitter.emit(”connection”); // Fire the data_received event eventEmitter.emit(”data_received”); console.log(“Program Ended.”); Output connection successful. data received successfully. Program Ended. Any asynchronous function in Node Application accepts a callback as the last parameter. The callback function accepts an error as the first parameter. Create a text file named input.txt with the following content. Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Create a js file named main.js having the following code − var fs = require(“fs”); fs.readFile(”input.txt”, function (err, data) { if (err) { console.log(err.stack); return; } console.log(data.toString()); }); console.log(“Program Ended”); Here fs.readFile() is a async function that read a file. If an error occurs during the read operation, then the err object will contain the corresponding error, else data will contain the contents of the file. readFile passes err and data to the callback function after the read operation is complete, which finally prints the content. Program Ended Tutorials Point is giving self learning content to teach the world in simple and easy way!!!!! Print Page Previous Next Advertisements ”;

Node.js – Callbacks Concept

Node.js – Callbacks Concept ”; Previous Next What is Callback? A Callback in Node.js is an asynchronous equivalent for a function. It is a special type of function passed as an argument to another function. Node.js makes heavy use of callbacks. Callbacks help us make asynchronous calls. All the APIs of Node are written in such a way that they support callbacks. Programming instructions are executed synchronously by default. If one of the instructions in a program is expected to perform a lengthy process, the main thread of execution gets blocked. The subsequent instructions can be executed only after the current I/O is complete. This is where callbacks come in to the picture. The callback is called when the function that contains the callback as an argument completes its execution, and allows the code in the callback to run in the meantime. This makes Node.js highly scalable, as it can process a high number of requests without waiting for any function to return results. The syntax of implementing callback in Node.js is as follows − function function_name(argument, function (callback_argument){ // callback body }) The setTimeout() function in Node.js is a typical example of callback. The following code calls the asynchronous setTimeout() method, which waits for 1000 milliseconds, but doesn”t block the thread. Instead, the subsequent Hello World message, followed by the timed message. Example setTimeout(function () { console.log(”This prints after 1000 ms”); }, 1000); console.log(“Hello World”); Output Hello World This prints after 1000 ms Blocking Code Example To understand the callback feature, save the following text as input.txt file. TutorialsPoint is the largest free online tutorials Library Master any technology. From programming languages and web development to data science and cybersecurity The following code reads the file synchronously with the help of readFileSync() function in fs module. Since the operation is synchronous, it blocks the execution of the rest of the code. var fs = require(“fs”); var data = fs.readFileSync(”input.txt”); console.log(data.toString()); let i = 1; while (i <=5) { console.log(“The number is ” + i); i++; } The output shows that Node.js reads the file, displays its contents. Only after this, the following loop that prints numbers 1 to 5 is executed. TutorialsPoint is the largest free online tutorials Library Master any technology. From programming languages and web development to data science and cybersecurity The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 Non-Blocking Code Example We use the same input.txt file in the following code to demonstrate the use of callback. TutorialsPoint is the largest free online tutorials Library Master any technology. From programming languages and web development to data science and cybersecurity The ReadFile() function in fs module is provided a callback function. The two arguments passed to the callback are error and the return value of ReadFile() function itself. The callback is invoked when ReadFile() finishes by returning either error or file contents. While the file read operation is inprocess, Node.js asynchronously runs the subsequent loop. var fs = require(“fs”); fs.readFile(”input.txt”, function (err, data) { if (err) return console.error(err); console.log(data.toString()); }); let i = 1; while (i <=5) { console.log(“The number is ” + i); i++; } Output The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 TutorialsPoint is the largest free online tutorials Library Master any technology. From programming languages and web development to data science and cybersecurity Callback as Arrow function You can also assign an arrow function as a callback argument. Arrow function in JavaScript is an anonymous function. It is also called as lambda function. The syntax of using arrow function as Node.js callback is as follows − function function_name(argument, (callback_argument) => { // callback body }) It was introduced in ES6 version of JavaScript. Let us replace the callback in the above example with an arrow function. var fs = require(“fs”); fs.readFile(”input.txt”, (err, data) => { if (err) return console.error(err); console.log(data.toString()); }); let i = 1; while (i <=5) { console.log(“The number is ” + i); i++; } The above code produces a similar output as the previous example. Print Page Previous Next Advertisements ”;