Search

NodeJS's Articles

Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside of a web browser.

Best Practices for Node.js Development: Tips and Tricks
Many developers nowadays prefer the Node.js framework to build websites and applications. Node.js is an advanced PHP framework that many big tech giants are using. Therefore, due to this change in the software landscape, there is a huge demand for Node.js framework to build web projects. The development of applications has been simplified by Node.js and its modules. Since Node.js allows developers to create applications both on the client and server simultaneously, it is highly versatile. However, creating and hosting applications are both different, as online scalability is totally dependent on what kind of infrastructure you use. MilesWeb is the leading Nodejs hosting provider offering compelling features and IT resources.  There are over a quarter of a million modules available in this framework. A Node.js application can be developed quickly and easily scaled thanks to its simplicity. Apart from Node JS one more popular web framework is Python. Several expert Python developers use the Python framework and their advanced version. We know that many of you will have the concern about which is suitable between Node js vs Python. For that, we recommend you to refer to online guides. Understanding the Mighty Event Loop  Node.js is so fast and brilliant because of the event loop. Because of this, it helps in utilizing the time efficiently or else it would have been wasted while waiting for input and output tasks to complete. If your Node.js application needs to do a CPU-intensive activity, such as computing, hashing passwords, or compressing, you'll also need to investigate possibilities for postponing the operation with setImmediate() or setTimeout in addition to the standard chore of spawning new processes for CPU-tasks. (). On the subsequent event loop cycle, the code in their callbacks will run again. Unfortunately, despite its name, nextTick() operates on the same cycle. Use Built-In Debugger  Debugging Node.js applications with the help of IDE integration in languages like Java or C# is a challenging task. Many Node.js developers are using the debugging pattern by making most of the console.log.  Apart from this, there are alternative methods also to debug Node.js applications. The essential one is Node.js is comprised of with own built-in debugger that runs by calling node to debug. Another interesting tool to debug Node.js apps is Node Inspector. Many branded tools are also available, but Built-In Debugger and Node-inspector have some interesting features, like live code changing, step debugging, and scope injection. Use npm Scripts To build, test, and even start the app, developers need to create npm scripts. Nowadays, it has become a standard option for testing Node.js applications. In fact, many developers look for this element while taking on new Node.js projects.  While developing front-end applications, there might be a scenario you have come across that is to run two or more processes to rebuild the code. For instance, you want to code for Webpack and nodemon. It is easy to achieve with the help of && (in the npm script) because the first command will not release the prompt. A module called Concurrently can handle this situation by spawning multiple processes at the same time. To avoid conflicts, you can also install development command-line tools locally, such as Webpack, nodemon, gulp, and Mocha.  Nodefly to Gauge the Performance Once the development process is completed, it the time to check its efficiency. Developers need to ensure all of their performance measures to check whether apps are running at an optimum speed or not. It is a logical step for any developer to monitor the node.js app's performance and profile. Nodefly is a service that allows developers to monitor the performance and profile of apps.  Nodefly will start to monitor the application for issues like memory leaks and measure how long it takes for Redis, mongo queries, and other essential stuff.  Lowercase is a king File names should match class names, of course. Files must, however, be lowercase. Some operating systems support both myclass.js and myclass.js, but Linux, for example, cannot. If you use lowercase in your Node.js code, you can reduce the time it takes to develop. Cluster your app It is important to be aware of the Node execution time limits, which lead to a huge waste of resources. Cluster support gives flexibility to developers to run the process on very little hardware.  Look deeper Node.js coding should be speed up by addressing the root cause, not just the surface level. The machine may be weak, the code may be flawed, or automatic scaling is not implemented. Identify the problem first and then determine how to proceed. You should also register the application's behavior, which will aid you in understanding the problem.
Nodejs Send Email with Attachment Tutorial
We will share with you in this article how to send an email with a file attachment in nodeJs using nodemailer package. mail send functionality is very common in nodejs application and you can be done using nodemailer. this is one of the best packages for work with mail sending in node js application. What is nodemailer Nodemailer is a module for Node.js applications to allow easy as cake email sending. The project got started back in 2010 when there was no sane option to send email messages, today it is the solution most Node.js users turn to by default. Before you can start or implement this code in your local system nodeJs must be installed in your system. If you never use before nodemailer in your nodejs application then don't worry we will here share with you all step by step. here we also have seen you how to configure Gmail mail setting in your nodemailer and how to send mail using your own Gmail account. Step - 1 Install Package First things we need to install a package in our nodejs application. first create one empty folder mailsenddemo for nodejs application. then go to your nodejs project root path and run npm init command for creating pakcage.json a file. then running the following command for install nodemailer package in your nodejs application. npm install nodemailer Make sure if you want to use the latest nodemailer package in your nodejs application then you installed nodejs version must be node.Js v6.0.0 Step - 2 Create index.js file Now, we need to create one index.js file in your project root directory. and write the following code into it. 'use strict'; const nodemailer = require('nodemailer'); // async..await is not allowed in global scope, must use a wrapper async function main() { // Generate test SMTP service account from ethereal.email // Only needed if you don't have a real mail account for testing let testAccount = await nodemailer.createTestAccount(); // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport({ host: 'smtp.ethereal.email', port: 587, secure: false, // true for 465, false for other ports auth: { user: testAccount.user, // generated ethereal user pass: testAccount.pass // generated ethereal password } }); // send mail with defined transport object let info = await transporter.sendMail({ from: '"Fred Foo 👻" <foo@example.com>', // sender address to: 'bar@example.com, baz@example.com', // list of receivers subject: 'Hello ✔', // Subject line text: 'Hello world?', // plain text body html: '<b>Hello world?</b>' // html body }); console.log('Message sent: %s', info.messageId); // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com> // Preview only available when sending through an Ethereal account console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info)); // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou... } main().catch(console.error); After doing this code in your index.js file and change your receivers and sender email id then run the following command in your terminal for a run this index.js file and check your code worked or not. node index.js After hitting the above command in your terminal then you can see the following output in your terminal. Message sent: <2f114f67-a092-a291-d12b-f43ce795c883@gmail.com> Preview URL: https://ethereal.email/message/Xaaj7HdneCuitgEMXaaj7wzb8CwPgbMbAAAAAYhvQhZDopLUBKHrXi7fzOg Then copy the Preview URL and open it in a new tab in your browser window. then you can see your sending mail content preview like that see the following image. Gmail Configuration If you want to use Gmail SMTP for send mail. and then that mail you want to send on your real Gmail account then do the following step. Just change the following code for the Gmail SMTP configuration. // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport({ host: 'smtp.gmail.com', port: 587, secure: false, // true for 465, false for other portss auth: { user: 'yourgmail@gmail.com', // generated ethereal user pass: 'your email account password' // generated ethereal password } }); Enable Less Secure Apps We also need to unable lesssecureapps functionality in your google Gmail account which you want to set in SMTP. just click on this link and enabled it Google Account Less Secure Apps Enable Then run your nodejs application again by running the following command. node index.js After running your index.js the file then now output will be the following in the terminal. Message sent: <058d5c5b-d72e-4e55-8008-5aa861d07334@gmail.com> Preview URL: false Here Preview URL is false so that mail content send on your gmail account. once check and confirm. Conclusion As you can see, how to send mail in node js with file attachment using nodemailer package is it very easy to implement in your node js application We hope that small tutorials help everyone.
Encrypt and Decrypt Data in NodeJS using Crypto
We will share with you in this article how to encrypt and decrypt data in node.js using crypto. Node.js provides the in-built library crypto for data encrypt and data decrypt. you can do any cryptographic opration help of crypto library on any srting, buffer and stream. as you know that very well data security in very important in web applications. In this article, we will show you examples of how you can do these encrypt and decrypt operations on data in your node.js applications. For a data encrypt and decrypt you can use multiple crypto algorithms. check out here official node.js docs link Crypto in Node.js. We will use AES (Advanced Encryption System) crypto algorithms in this article for data encrypt and decrypt. Step - 1 Create a new node.js project First, we need to create one Node.js application in our system. you can create fresh new node.js application anywhere in your system then go to the node.js application's root path and create pakcage.js file help of the following command. npm init -y Step - 2 Install Package (Optional) This step is optional if you have installed a new version of Node.js. crypto has in-built in the new Node.js version. Now, the second thing is an install crypto package in your Node.js application. you can install crypto package help of run the following command in your project's root directory. npm install crypto --save Step - 3 Encrypt and decrypt data (Strings, numbers etc) Now we will see some example demo code of how to encrypt and decrypt on string and numbers. you can check the following examples. just put the following code in your index.js file. // Nodejs encryption examples with CTR const crypto = require('crypto'); const algorithm = 'aes-256-cbc'; const key = crypto.randomBytes(32); const iv = crypto.randomBytes(16); function encrypt(text) { let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv); let encrypted = cipher.update(text); encrypted = Buffer.concat([encrypted, cipher.final()]); return { iv: iv.toString('hex'), encryptedData: encrypted.toString('hex') }; } function decrypt(text) { let iv = Buffer.from(text.iv, 'hex'); let encryptedText = Buffer.from(text.encryptedData, 'hex'); let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv); let decrypted = decipher.update(encryptedText); decrypted = Buffer.concat([decrypted, decipher.final()]); return decrypted.toString(); } var hw = encrypt("Let's do this encrypt and decrypt.") console.log(hw) console.log('Your decrypt string is : '+ decrypt(hw)) Below example, we just create two functions one for encrypt data and a second one for decrypt data. now you can run and see the output help of run the following command. node index.js Here is the output: Your output looks like in your terminal window. { iv: '5367a0bc7b47ade7862925398e4e8811', encryptedData: '8295c8028c6c823ef0a475fae424c07b975c60400ddb079f2b326e8f49108d70ba5839120bd3725956bdb18f2ecd7df6' } Your decrypt string is : Let's do this encrypt and decrypt. Step - 4 Encrypt and decrypt buffer Now, we will see how to work encrypt and decrypt on buffer. we can use our below encrypt and decrypt function also in buffer operations. just here one example. Like this. var hw = encrypt(Buffer.from("Some serious stuff","utf-8")) console.log(hw) console.log(decrypt(hw)) Conclusion As you can see, encrypt and decrypt data in Node.js it is very easy to use and implement in Node.js application help of crypto. We hope that small tutorials help everyone.
Password Hashing and Verify in NodeJS using Bcrypt
In this article, we will share with you how to hashing the password and compare password string with hashing password string help of bcrypt. bcrypt library provides you with making a password in a hash string and normal string compares with hashing string in node.js applications. Nodejs provides crypto modules to perform the encryption and hashing of sensitive information such as passwords. The Bcrypt node modules provides an easy way to create and compare hashes. bcrypt the module provides both synchronous and asynchronous methods for work with any string make hashing and any normal string compare with already hashsing formate. so, it will help lots in our node.js application current password check with already store hashed password in our database. Examples const bcrypt = require('bcrypt'); bcrypt.hash('Your_password', 10, function(err, hash) { console.log(hash); // output will be // $2b$10$wV1ndcFMmu/6Ue4Tuy2OqeSIEQKrjnYMlBCMOG66nBnWk2TUFGDL. }); bcrypt.compare('Your_password', '$2b$10$wV1ndcFMmu/6Ue4Tuy2OqeSIEQKrjnYMlBCMOG66nBnWk2TUFGDL.', function(err, res) { if(res) { console.log('Your password mached with database hash password'); } else { console.log('Your password not mached.'); } }); Conclusion As you can see, password hashing and normal password string compare with existing hashing string it is very easy to use or check the help of bcrypt library. We hope that small tutorials help everyone.
Create and send get request in Node.js
Node.js built-in HTTP module is used to transfer data over http protocol. It can send HTTP request to external server and get response data. There are two ways, to send get request from http module. We will see both method one by one. http.get() method To use the HTTP module, use require() method to import module. const http = require('http'); http's get method is used to send get request. http.get(url, options, callback); // or http.get(options, callback); url: required where get request is send. Pass data into query string.  options: optional is object that is sent with request. callback: function that accept response which is object of http.IncomingMessage calback object's res.on() 'data' event receive data into chunk and end method completes request. const https = require('https'); rawdata = ''; // send request data https.get('https://jsonplaceholder.typicode.com/todos/1', (res) => {     // append response to variable     res.on('data', (chunk) => {         rawdata += chunk;     });     // print response data     res.on('end', () => {         try {             const parsedData = JSON.parse(rawdata);             console.log(parsedData);         } catch (e) {             connsole.log(e.message);         }     }); }).on('error', (e) => {     console.error(e.message); }); We receive the string data in response, so we need to convert response to json data using JSON.parse() method. http.request() method http.request(url, options, callback); // or http.request(options, callback); url: required where get request is send. You can pass this into options object. options: optional is object that is sent with request. callback: function that accept response which is object of http.ClientRequest In this method, you define request type into options object. In the below example, We have also set url into options object with headers. const https = require('https'); rawdata = ''; const options = {     hostname: 'jsonplaceholder.typicode.com',     path: '/todos/1',     method: 'get',     headers: {         'Content-Type': 'text/html'     } } // send request data const req = https.request(options, (res) => {     // append response to variable     res.on('data', (chunk) => {         rawdata += chunk;     });     // print response data     res.on('end', () => {         console.log(rawdata);     }); }); req.on('error', (e) => {     console.error(e.message); }); req.end(); Note that in this method, we should call req.end() to define end of the request. If any error occurs, it will listen on error event. In this article, we have learned to create http get request and send to the external server. In the next article, we will use post methods of http module.
How To Create a Web Server in Node.js with the HTTP Module
Node.js has built-in HTTP module to transfer data over http protocol. HTTP module also used to create http server and send response to the specific server port. To use the HTTP module, use require() method to import module. const http = require('http'); Now use createServer() method to create HTTP server and listen() method listen to the given port. Here is the example. Create file http.js and save the below code into it. const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer(function(req, res) {     res.write('Hello World!\n');     res.end(); }); server.listen(port, hostname, function() {     console.log(`Server running at http://${hostname}:${port}/`); }); Now run the file into node from Terminal. node http.js You will see below console message into response. Server running at http://127.0.0.1:3000/ Open the browser and input url http://127.0.0.1:3000/. The server will response the data that we passed in res.write() method. You can also send response header using res.writeHead() method. The below example will return 'Content-Type': 'text/html' header in response. const http = require('http'); const server = http.createServer(function(req, res) {     res.writeHead(200, {'Content-Type': 'text/html'});     res.write('<h1>Hello World!</h1>');     res.end(); }).listen(3000); In this article, we have learned to create http server and send response data with header. In the next article, we will use other methods of http module.
Node.js MySQL Delete data Database Table
In this tutorial article, we will see how to delete data from MySQL database using Node.js. We will use where condition to delete specific records from MySQL server.  Perform the following steps to delete data from MySQL database server. Step 1: First create connection between MySQL server and Node.js. Step 2: After database connection created, use conn.query() method to run DELETE query into MySQL database. var query = `DELETE FROM visitors WHERE percentage < ?`; var percentage = 50; After the query executed, close the connection using conn.end() method. We have created below delete_rows.js file with full example. const mysql = require('mysql'); const conn = mysql.createConnection({     host: 'localhost',     port: 3306,     database: 'charts',     user: 'root',     password: 'root', }); conn.connect((err) => {     if (err) {         return console.log(err.message);     } else {         // select query         var query = `DELETE FROM visitors WHERE percentage < ?`;         var percentage = 50;         // query to database         conn.query(query, percentage, function(err, response, result) {             if (err) {                 return console.log(err.message);             } else {                 console.log(response);             }         });     }     // close the connection     conn.end(); }); Now run the file into Node server. node delete_rows.js The application will response with object data. In the database all records will be deleted with percentage less than 50. OkPacket {   fieldCount: 0,   affectedRows: 6,   insertId: 0,   serverStatus: 34,   warningCount: 0,   message: '',   protocol41: true,   changedRows: 0 } You can get number of deleted records using response.affectedRows object property. Note: If you omit the WHERE condition, all records will be deleted.
Node.js MySQL Update data Database Table
In this tutorial article, we will learn how to update data from MySQL database using Node.js. We will use where condition to update specific records into MySQL server.  Perform the following steps to update data into MySQL database server. Step 1: First create connection between MySQL server and Node.js. Step 2: After database connection created, use conn.query() method to run UPDATE query into MySQL database. var query = `UPDATE visitors SET percentage = ? WHERE id = ?`; var percentage = [62.02, 1]; Step 3: After the query executed, close the connection using conn.end() method. We have created below update_rows.js file with full example. const mysql = require('mysql'); const conn = mysql.createConnection({     host: 'localhost',     port: 3306,     database: 'charts',     user: 'root',     password: 'root', }); conn.connect((err) => {     if (err) {         return console.log(err.message);     } else {         // select query         var query = `UPDATE visitors SET percentage = ? WHERE id = ?`;         var percentage = [62.02, 1];         // query to database         conn.query(query, percentage, function(err, response, result) {             if (err) {                 return console.log(err.message);             } else {                 console.log(response);             }         });     }     // close the connection     conn.end(); }); Now run the file into Node server. node update_rows.js The application will response with object data. OkPacket {   fieldCount: 0,   affectedRows: 1,   insertId: 0,   serverStatus: 2,   warningCount: 0,   message: '(Rows matched: 1  Changed: 1  Warnings: 0',   protocol41: true,   changedRows: 1 } You can get updated records number using response.affectedRows object property. Note: If you omit the WHERE condition, all records will be updated.