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 ”;

Node.js – Console

Node.js – Console ”; Previous Next A console is a text-based user interface that allows you to interact with the computer”s operating system or run code. With the console, you can write and execute commands or programs. It is also used for debugging and troubleshooting. The built-in library of Node.js includes the Console module. It provides functionality to print messages to IO streams, a functionality similar to the JavaScript console mechanism provided by web browsers. The Console module’s functionality has two major parts − Console class: The console class methods are console.log(), console.error() and console.warn() to display Node.js stream. global console object: A predefined object that echoes logging, errors and warning messages to the standard output stream. It is used without calling require(‘console’). The default usage of global console object is simple. The following code shows a typical usage of global console object to display logging, error and warning messages. Example // Welcome message console.log(”Welcome to Tutorialspoint!”); // Hello world message console.log(”hello world”); // printing to error stream console.error(new Error(”Oops… something went wrong”)); // print warning const name = ”NodeJS Tutorial”; console.warn(`Warning ${name}! Warning!`); Output Welcome to Tutorialspoint! hello world Error: Oops… something went wrong at Object.<anonymous> (D:nodejsemailappmain.js:11:15) at Module._compile (node:internal/modules/cjs/loader:1241:14) at Module._extensions..js (node:internal/modules/cjs/loader:1295:10) at Module.load (node:internal/modules/cjs/loader:1091:32) at Module._load (node:internal/modules/cjs/loader:938:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12) at node:internal/main/run_main_module:23:47 Warning NodeJS Tutorial! Warning! You can also customize the console object by designating the streams for reflecting the output and error logs. Declare an object of Console class and pass the stream objects as arguments. The program below redirects the logs and errors to the two disk files. const fs = require(”fs”); const out = fs.createWriteStream(”./stdout.log”); const err = fs.createWriteStream(”./stderr.log”); const logger = new console.Console(out, err); // Welcome message logger.log(”Welcome to Tutorialspoint!”); // Hello world message logger.log(”hello world”); // printing to error stream logger.error(new Error(”Oops… something went wrong”)); // print warning const name = ”NodeJS Tutorial”; logger.warn(`Warning ${name}! Warning!`); This will create two files stdout.log and stderr.log in the current directory, with the result of log(), error(), and warn() methods of console objects saved in them. Console Methods Following is a list of methods available with the console object. Sr.No. Method & Description 1 console.log([data][, …]) Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. 2 console.info([data][, …]) Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. 3 console.error([data][, …]) Prints to stderr with newline. This function can take multiple arguments in a printf()-like way. 4 console.warn([data][, …]) Prints to stderr with newline. This function can take multiple arguments in a printf()-like way 5 console.dir(obj[, options]) Uses util.inspect on obj and prints resulting string to stdout. 6 console.time(label) Mark a time. 7 console.timeEnd(label) Finish timer, record output. 8 console.trace(message[, …]) Print to stderr ”Trace :”, followed by the formatted message and stack trace to the current position. 9 console.assert(value[, message][, …]) Similar to assert.ok(), but the error message is formatted as util.format(message…). nodejs_global_objects.htm Print Page Previous Next Advertisements ”;

Node.js – Upload Files

Node.js – Upload Files ”; Previous Next In many web applications, a user from client machine is required to upload file (such as the user uploading images and videos with Facebook or Instagram apps) to the server. There are a number of open-source modules available on the NPM registry, with which the feature of uploading files can be enabled in a Node.js application. The formidable module offers a convenient API to handle the file uploads. The formidable module can be imported in a core Node.js module along with the built-in http module, as well as the Express app. Formidable The Formidable module is a fast and streaming multipart parser, capable of automatically writing file uploads to the disk. It has a low memory footprint, with efficient error handling mechanism. As a first step, install the formidable module with the following command − npm install formidable In this chapter, the example usage of Formidable module in a node.js application that includes http module and in an ExpressJs application are shown below − with Node.js http module The following example calls the createServer() function to launch the Node.JS server and renders a multipart HTML form for the user to choose the file to be uploaded. When the file is submitted, the form data is parsed and the uploaded file is copied in the default location in the disk. var http = require(”http”); var formidable = require(”formidable”); var errors = formidable.formidableErrors; const server = http.createServer(async (req, res) => { if (req.url === ”/api/upload” && req.method.toLowerCase() === ”post”) { // parse a file upload const form = new formidable.IncomingForm(); let fields; let files; try { [fields, files] = await form.parse(req); } catch (err) { res.writeHead(err.httpCode || 400, { ”Content-Type”: ”text/plain” }); res.end(String(err)); return; } res.writeHead(200, { ”Content-Type”: ”application/json” }); res.end(JSON.stringify({ fields, files }, null, 2)); return; } // show a file upload form res.writeHead(200, { ”Content-Type”: ”text/html” }); res.end(` <h2>With Node.js <code>”http”</code> module</h2> <form action=”/api/upload” enctype=”multipart/form-data” method=”post”> <div>Text field title: <input type=”text” name=”title” /></div> <div>File: <input type=”file” name=”multipleFiles” multiple=”multiple” /></div> <input type=”submit” value=”Upload” /> </form> `); }); server.listen(5000, () => { console.log(”Server listening on http://localhost:5000/ …”); }); As the application is run, the browser shows the following form to choose a file to be uploaded. After successful upload operation, the browser shows the following result − { “fields”: { “title”: [ “test” ] }, “files”: { “multipleFiles”: [ { “size”: 4203211, “filepath”: “C:\Users\user\AppData\Local\Temp\930f2f754006b790729e0d200”, “newFilename”: “930f2f754006b790729e0d200”, “mimetype”: “image/png”, “mtime”: “2023-12-24T08:04:09.856Z”, “originalFilename”: “1.png” } ] } } with Express.js The simplest usage of formidable module in an Express.JS code is as follows − import express from ”express”; import formidable from ”formidable”; const app = express(); app.get(”/”, (req, res) => { res.send(` <h2>With <code>”express”</code> npm package</h2> <form action=”/api/upload” enctype=”multipart/form-data” method=”post”> <div>Text field title: <input type=”text” name=”title” /></div> <div>File: <input type=”file” name=”someExpressFiles” multiple=”multiple” /></div> <input type=”submit” value=”Upload” /> </form> `); }); app.post(”/api/upload”, (req, res, next) => { const form = formidable({}); form.parse(req, (err, fields, files) => { if (err) { next(err); return; } res.json({ fields, files }); }); }); app.listen(5000, () => { console.log(”Server listening on http://localhost:5000 …”); }); You can also install and use body-parser module to parse the multipart HTML form data in the uploading process. Multer Another useful NPM module that is capable of handling file uploads is called Multer. Users can upload either single or multiple files at a time. To install, use the following command − npm install multer In the beginning of an Express app, include muletr and declare the Multer object. const multer = require(”multer”) const upload = multer({ dest: ”uploads/” }) Assuming that you have a route to handle a GET request and display a multipart HTML form that posts the form to /upload route, add the following function to handle POST request − app.post(“/upload”, upload.single(“myFile”), (req, res) => { console.log(“Body: “, req.body); console.log(“File: “, req.file); res.send(“File successfully uploaded.”); }); To store the uploaded file at a specified location instead of the default location of the temporary file, configure the Multer location as below − var storage = multer.diskStorage({ destination: function(req, file, cb) { // destination is used to specify the path of the directory in which the files have to be stored cb(null, ”./uploads”); }, filename: function (req, file, cb) { // It is the filename that is given to the saved file. cb(null , file.originalname); } }); // Configure storage engine instead of dest object. const upload = multer({ storage: storage }) Print Page Previous Next Advertisements ”;