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

Node.js – MongoDB Create Collection

Node.js – MongoDB Create Collection ”; Previous Next A MongoDB database is made up of one or more Collections. A Collection is a group of document objects. Once a database is created on the MongoDB server (a standalone server or a on a shared cluster in MongoDB Atlas), you can then create Collections in it. The mongodb driver for Node.js has a cerateCollection() method, that returns a Collection object. Collection in MongoDB is similar to the table in a relational database. However, it doesn”t have a predefined schema. Each document in a collection may consist of variable number of k-v pairs not necessarily with same keys in each document. To create a collection, get the database object from the database connection and call the createCollection() method. db.createCollection(name: string, options) The name of the collection to create is passed as the argument. The method returns a Promise. Collection namespace validation is performed server-side. const dbobj = await client.db(dbname); const collection = await dbobj.createCollection(“MyCollection”); Note that the collection is implicitly created when you insert a document in it even if it is not created before insertion. const result = await client.db(“mydatabase”).collection(“newcollection”).insertOne({k1:v1, k2:v2}); Example The following Node.js code creates a Collection named MyCollection in a MongoDB database named mydatabase. 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(); await newcollection(client, “mydatabase”); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function newcollection (client, dbname){ const dbobj = await client.db(dbname); const collection = await dbobj.createCollection(“MyCollection”); console.log(“Collection created”); console.log(collection); } The MongoDB Compass shows that the MyCollection is created in mydatabase. You can also verify the same in MongoDB shell. > use mydatabase < switched to db mydatabase > show collections < MyCollection Print Page Previous Next Advertisements ”;

Node.js – MySQL Select From

Node.js – MySQL Select From ”; Previous Next The most frequent operation performed on a MySQL database is retrieval of data from the tables. The SELECT query corresponds to the Retrieve action in the CRUD acronym. To perform retrieval with a Node.js program, the SELECT query string should be passed to the query() method of MySQL connection object. The SELECT FROM statement in MySQL has the following syntax − SELECT field1, field2, … FROM table_name; To select data from all the fields defined in the table, you can use the Asterix (*) character. SELECT * FROM table_name; There are additional clauses that can be used with the primary SELECT statement, such as LIKE, WHERE, ORDER BY etc. The SELECT statement returns a resultset, containing the list of rows retrieved from the table. The MySQL command-line client is like the Node.js REPL environment. The resultset retrieved by the SELECT statement is displayed immediately after the query statement. mysql> use mydb; Database changed mysql> SELECT name, age, salary FROM employee; +——-+——+——–+ | name | age | salary | +——-+——+——–+ | Ravi | 25 | 25000 | | Anil | 26 | 30000 | | Meena | 26 | 27000 | +——-+——+——–+ However, with Node.js, when the SELECT query is passed to the query() method of MySQL connection object, it returns an array of RowDataPacket objects. To process the retrieved data, it must be JSONified. Example In the following code, we pass the SELECT query string to the con.query() method and display the resultset on the console. var mysql = require(”mysql”); var con = mysql.createConnection({ host: “localhost”, user: “root”, password: “mypassword”, database: “mydb” }); var qry =`SELECT name,salary FROM employee;`; con.connect(function (err) { if (err) throw err; console.log(“Connected!”); con.query(qry, function (err, results) { if (err) throw err; console.log(results); }); con.end(); }); Output [ RowDataPacket { name: ”Ravi”, salary: 25000 }, RowDataPacket { name: ”Anil”, salary: 30000 }, RowDataPacket { name: ”Meena”, salary: 27000 } ] Instead of the raw resultset, we can use the JSON.stringify() method to convert the RowDataPacket object to string. var qry =`SELECT name,salary FROM employee;`; con.connect(function (err) { if (err) throw err; console.log(“Connected!”); con.query(qry, function (err, results) { if (err) throw err; console.log(JSON.stringify(results)); }); con.end(); }); Output [{“name”:”Ravi”,”salary”:25000},{“name”:”Anil”,”salary”:30000},{“name”:”Meena”,”salary”:27000}] Example In this example, the * wild card is used to retrieve data from all the fields in employee table. We also employ forEach loop to iterate row-wise over the resultset returned by SELECT query. The value of each field in the row is fetched by the putting the field-name in the square brackets. For example, the ID of a row is given by row[‘id’]. var mysql = require(”mysql”); var con = mysql.createConnection({ host: “localhost”, user: “root”, password: “mypassword”, database: “mydb” }); var qry =`SELECT * FROM employee;`; 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(`ID: ${row[”id”]}, NAME: ${row[”name”]}, AGE: ${row[”age”]}, SALARY: ${row[”salary”]}`); }); }); con.end(); }); Output ID: 1, NAME: Ravi, AGE: 25, SALARY: 25000 ID: 2, NAME: Anil, AGE: 26, SALARY: 30000 ID: 3, NAME: Meena, AGE: 26, SALARY: 27000 You can include derived or computed column in the field list of SELECT statement, where its value depends on an expression involving the fields defined in the structure. You can also give an alias name to a field with AS keyword. SELECT expression AS COLUMN_name FROM table_name; In the following example, the SELECT statement has a TAX column. Its value is computed as 5 percent of salary field. var mysql = require(”mysql”); var con = mysql.createConnection({ host: “localhost”, user: “root”, password: “mypassword”, database: “mydb” }); var qry =`SELECT name, salary, salary*0.05 as tax FROM employee;`; con.connect(function (err) { if (err) throw err; console.log(“Connected!”); con.query(qry, function (err, results) { if (err) throw err; console.log(JSON.stringify(results)); }); con.end(); }); Output [{“name”:”Ravi”,”salary”:25000,”tax”:1250},{“name”:”Anil”,”salary”:30000,”tax”:1500},{“name”:”Meena”,”salary”:27000,”tax”:1350}] Print Page Previous Next Advertisements ”;

Node.js – Packaging

Node.js – Packaging ”; Previous Next A large-sized Node.js project usually has a number of dependencies and a number of source files as well as other assets such as images, web pages, setting files etc. To distribute a Node.js project and deploy it on any other environment becomes difficult, and hence it needs to packaged so that it can be easily ported to other machine. There are a number of packaging tools available on NPM repository. This chapter discusses nexe packaging tool, and also takes overview of some other packaging libraries. Nexe To demonstrate how the Nexe utility works, we shall an ExpressJs app with the following script − Index.js var express = require(”express”); var app = express(); var path = require(”path”); var bodyParser = require(”body-parser”); // Create application/x-www-form-urlencoded parser var urlencodedParser = bodyParser.urlencoded({ extended: false }) app.use(express.static(”public”)); app.get(”/”, function (req, res) { res.sendFile(path.join(__dirname,”index.html”)); }) app.get(”/process_get”, function (req, res) { // Prepare output in JSON format response = { first_name:req.query.first_name, last_name:req.query.last_name }; console.log(response); res.end(JSON.stringify(response)); }) app.post(“/process_post”, ) var server = app.listen(5000, function () { console.log(“Express App running at http://127.0.0.1:5000/”); }) The ‘/’ route renders a HTML form from the following script − Index.html <html> <body> <form action = “/process_POST” method = “POST”> First Name: <input type = “text” name = “first_name”> <br> Last Name: <input type = “text” name = “last_name”> <br> <input type = “submit” value = “Submit”> </form> </body> </html> The Node.js server displays the following form − The Node.js application above also registers the static middleware, hence it displays an image placed in static/images folder. We now want to build a self-executable for this Node.js app containing the code, the subdirectories as well as the assets in a single file. Nexe is a command-line utility that compiles your Node.js application into a single executable file. Features of Nexe Self contained applications Ability to run multiple applications with different node.js runtimes. Distribute binaries without needing node / npm. Start and deploy faster. Flexible build pipeline Cross platform builds Install Nexe on Windows Perform global installation of Nexe as follows − npm install nexe -g You also need Netwide Assembler (NASM) tool. Download and install the same from www.nasm.us The nexe utility requires Python installed on the system. Ensure that Python is one of the versions 3.11 to 3.7. Assuming that you are using nexe for 64-bit Windows OS, you also need to install The “Desktop development with C++” workload from Visual Studio 2022. It can be installed from aka.ms. (For other OS platforms, follow the instructions on github.com/nodejs Once all the prerequisites are installed, run the following command in the CMD terminal − D:expressApp>nexe index.js –build windows-x64-20.9.0 –verbose The compilation may take a while, but in the end, it will create expressApp.exe in the application folder. D:expressApp │ expressApp.exe │ index.html │ index.js │ package-lock.json │ package.json │ users.json │ ├───node_modules │ │ .package-lock.json │ ├───body-parser │ │ │ HISTORY.md │ │ │ index.js │ │ │ LICENSE │ │ │ package.json │ │ │ README.md │ │ │ SECURITY.md │ │ │ . . . │ │ │ . . . │ │ │ . . . │ ├───express │ │ │ History.md │ │ │ index.js │ │ │ LICENSE │ │ │ package.json │ │ │ Readme.md │ │ │ . . . │ │ │ . . . │ │ │ . . . └───public └───images logo.png Run it from the command line, and the Node.js server starts. D:expressApp>expressapp Express App running at http://127.0.0.1:5000/ pkg tool The pkg tool is a command-line interface that enables the developer to create executables from Node.JS projects; allowing you to run the app even on environments that do not have Node.JS installed on them. To install pkg, use the command − npm install -g pkg Then use pkg to build the executable pkg myapp.js Running the above command will generate three programmes; namely an executable for Windows, macOS, and Linux. More details can be found at www.npmjs.com. JXCore JXcore, which is an open source project, introduces a unique feature for packaging and encryption of source files and other assets into JX packages. Download and install the JXcore package from https://github.com/jxcore, as per your operating system and machine architecture. To package the above project, you simply need to go inside this directory and issue the following jx command. Assuming index.js is the entry file for your Node.js project − jx package index.js index the above command will pack everything and will create the following two files − index.jxp − This is an intermediate file which contains the complete project detail needed to compile the project. index.jx − This is the binary file having the complete package that is ready to be shipped to your client or to your production environment. Consider your original Node.js project was running as follows − node index.js command_line_arguments After compiling your package using JXcore, it can be started as follows − jx index.jx command_line_arguments Print Page Previous Next Advertisements ”;

Node.js – MongoDB Get Started

Node.js – MongoDB Get Started ”; Previous Next In this chapter, we shall learn to use MongoDB as a backend with Node.js application. A Node.js application can be interfaced with MongoDB through the NPM module called mongodb itself. MongoDB is a document-oriented NOSQL database. It is an open-source, distributed and horizontally scalable schema-free database architecture. Since MongoDB internally uses JSON-like format (called BSON) for data storage and transfer, it is a natural companion of Node.js, itself a JavaScript runtime, used for server-side processing. Installation MongoDB server software is available in two forms: Community edition and Enterprise edition. The MongoDB community edition is available for Windows, Linux as well as MacOS operating systems at https://www.mongodb.com/try/download/community Windows Download the latest version of MongoDB installer (https://fastdl.mongodb.org/windows/mongodb-windows-x86_64-7.0.4-signed.msi) and start the installation wizard by double-clicking the file. Choose Custom installation option to specify a convenient installation folder. Uncheck the “Install MongoD as service” option, and accept the default data and log directory options. Go through the rest of steps in the installation wizard. Create a directory “d:datadb” and specify it as dbpath in the following command-line to start the MongoDB server − “D:mongodb7mongod.exe” –dbpath=”d:datadb” The installer also guides you to install MongoDB Compass, a GUI client for interacting with the MongoDB server. MongoDB server starts listening to the incoming connection requests at the 27017 port by default. Start the Compass app, and connect to the server using the default connection string as ”mongodb://localhost:27017”. Ubuntu To install MongoDB server on Ubuntu Linux, issue the following command to reload the local package database − sudo apt-get update You can now install either the latest stable version of MongoDB or a specific version of MongoDB. To install the latest stable version, issue the following sudo apt-get install -y mongodb-org mongodb driver Now we need to install the mongodb driver module from the NPM repository, so that a Node.js application could interact with MongoDB. Initialize a new Node.js application in a new folder with the following command − D:nodejsmongoproj>npm init -y Wrote to D:nodejsmongoprojpackage.json: { “name”: “mongoproj”, “version”: “1.0.0”, “description”: “”, “main”: “index.js”, “scripts”: { “test”: “echo “Error: no test specified” && exit 1″ }, “keywords”: [], “author”: “”, “license”: “ISC” } Install the mongodb driver module from NPM repository with the following command − D:nodejsmongoproj>npm install mongodb Connecting to MongoDB Now we can establish connection with MongoDB server. First, import the MongoClient class from the mongodb module with the require() statement. Call its connect() method by passing the MongoDB server URL. const { MongoClient } = require(”mongodb”); // Connection URL const url = ”mongodb://localhost:27017”; const client = new MongoClient(url); // Database Name const dbName = ”myProject”; async function main() { // Use connect method to connect to the server await client.connect(); console.log(”Connected successfully to server”); const db = client.db(dbName); const collection = db.collection(”documents”); // the following code examples can be pasted here… return ”done.”; } main() .then(console.log) .catch(console.error) .finally(() => client.close()); Assuming that the above script is saved as app.js, run the application from command prompt − PS D:nodejsmongoproj> node app.js Connected successfully to server done. Print Page Previous Next Advertisements ”;

Node.js – REPL Terminal

Node.js – REPL Terminal ”; Previous Next The Node.js runtime has a built-in interactive shell, in which you can execute instructions one at a time. The Node.js interactive shell works on the principle of REPL, which is an acronym for READ, EVALUATE, PRINT and LOOP. The Node.js interactive REPL terminal is like the Powershell or Command prompt terminal, or a bash terminal in Linux. It performs the following tasks − Read − Reads user”s input, parses the input into JavaScript data-structure, and stores in memory. Eval − Takes and evaluates the data structure. Print − Prints the result. Loop − The terminal is ready to receive next input from the user. To simplify your learning, we have set up an easy to use Node.js REPL environment online, where you can practice Node.js syntax − To launch Node.js REPL Terminal, visit Node.Js Terminal To start the Node.js REPL on your computer, simply enter node in the command terminal (without the javascript file name as done before). The Node.js prompt > will appear. D:nodejs>node Welcome to Node.js v20.9.0. Type “.help” for more information. > The REPL feature of Node is very useful in experimenting with Node.js codes and to debug JavaScript codes. You can test any Node.js/JavaScript expression by entering in front of the > prompt. For example − > 10+20 30 > “Hello”+”World” ”HelloWorld” > a=10 10 > b=20 20 > a+b 30 > Math.random() 0.5423940959293392 > You can see that the instruction is read, evaluated, its result displayed and the terminal is ready to receive next instruction. To start the REPL, press ctrl+c twice, or ctrl+D, or enter .exit in front of > symbol. Multiline Expression Node REPL supports multiline expression similar to JavaScript. Let”s check the following do-while loop in action − > x=0 0 > do { … x++; … console.log(“x: “+x); … } … while (x<5); x: 1 x: 2 x: 3 x: 4 x: 5 undefined > The three dots … comes automatically when you press Enter after the opening bracket. Node automatically checks the continuity of expressions. Underscore Variable You can use underscore (_) to get the last result − > var x=10 undefined > var y=20 undefined > x+y 30 > var z= _ undefined > z 30 > Dot commands The REPL has some special commands, all starting with a dot .. They are Sr.No Dot Commands & Description 1 .help shows the dot commands help 2 .editor enables editor mode, to write multiline JavaScript code with ease. Once you are in this mode, enter ctrl-D to run the code you wrote. 3 .break when inputting a multi-line expression, entering the .break command will abort further input. Same as pressing ctrl-C. 4 .clear resets the REPL context to an empty object and clears any multi-line expression currently being input. 5 .load loads a JavaScript file, relative to the current working directory 6 .save saves all you entered in the REPL session to a file (specify the filename) 7 .exit exits the repl (same as pressing ctrl-C two times) 8 Up/Down Keys see command history and modify previous commands. 9 tab Keys list of current commands. Print Page Previous Next Advertisements ”;

Node.js – MongoDB Create Database

Node.js – MongoDB Create Database ”; Previous Next MongoDB is an open-source, cross-platform document-oriented database environment. MongoDB uses JSON-like, schema-free documents. More than one documents form a collection, and one or more collections may be present in a MongoDB database. In this chapter, we whall learn how to create a MongoDB database with a Node.js application. The MongoDB database management software is available in the following three editions − MongoDB Community − The source-available, free-to-use, and self-managed version of MongoDB, available for local installation, available for Windows, Linux, and macOS. MongoDB Enterprise − A commercial, subscription-based, self-managed version of MongoDB, with a lot of advanced features than the community edition. MongoDB Atlas − An on-demand, fully managed service for MongoDB deployments in the cloud. It runs on AWS, Microsoft Azure, and Google Cloud Platform. Connection strings The mongodb driver for Node.js is imported into the code with the require() function. The object of MongoClient class represents a database connection. You need to pass a connection string to its constructor. const { MongoClient } = require(”mongodb”); const client = new MongoClient(ConnectionString); The MongoDB connection string must be one of the following formats − Standard Connection String Format − This format is used to connect to a self-hosted MongoDB standalone deployment, replica set, or sharded cluster. The standard URI connection scheme has the form − mongodb://[username:password@]host1[:port1][,…hostN[:portN]][/[defaultauthdb][?options]] The default connection string is − mongodb://localhost:27017/ SRV Connection Format − A connection string with a hostname that corresponds to a DNS SRV record. MongoDB Atlas uses SRV connection format. MongoDB supports a DNS-constructed seed list. It allows more flexibility of deployment and the ability to change the servers in rotation without reconfiguring clients. The SRV URI connection scheme has the following form − mongodb+srv://[username:password@]host[/[defaultauthdb][?options]] Here is an example of SRV connection string − const uri = “mongodb+srv://user:[email protected]/?retryWrites=true&w=majority”; In the following example, we are using the standard connection string to fetch the list of databases. Example: List of databases The connect() method of MongoClient object returns a Promise. The call to connect() method is asynchronous. Next a function listdatabases() is called. 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 await listDatabases(client); } catch (e) { console.error(e); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function listDatabases(client) { databasesList = await client.db().admin().listDatabases(); console.log(“Databases:”); databasesList.databases.forEach(db => console.log(` – ${db.name}`)); }; Output Databases: – admin – config – local – myProject – mydb Create a new database To create a new database on the server, you need to call the db() method of MongoClient class. var dbobj = client.db(database_name, options); The db() method returns a db instance that represents the database on the server. In the following example, we have demonstrated how to create a new database named as mydatabase in MongoDB. const {MongoClient} = require(”mongodb”); async function main(){ const uri = “mongodb://localhost:27017/mydb”; const client = new MongoClient(uri); try { // Connect to the MongoDB cluster await client.connect(); await createdb(client, “mydatabase”); } finally { // Close the connection to the MongoDB cluster await client.close(); } } main().catch(console.error); async function createdb(client, dbname){ const dbobj = await client.db(dbname); console.log(“Database created”); console.log(dbobj); } However, note that the database is not physically created on the server till at least one collection is created and there should be at least one document in it. Print Page Previous Next Advertisements ”;

Node.js – Environment Setup

Node.js – Environment Setup ”; Previous Next Node.js Environment Setup This Node.js tutorial consists of a number of ready-to-run examples, so that the learn can understand the Node.js concepts by running the code. To be able to execute the example code, you can use our online Node.js environment, or install Node.js environment in your local machine. Try it Option Online You really do not need to set up your own environment to start learning Node.js. Reason is very simple, we already have set up Node.js environment online, so that you can execute all the examples in this tutorial online and learn through practice. Try the following example using the Live Demo option available at the top right corner of the below code box (on our website) /* Hello World! program in Node.js */ console.log(“Hello World!”); When you click the Live Demo button, the online Node.js environment is opened in a new browser tab. Feel free to modify any example and check the results with different options. For most of the examples given in this tutorial, you will find a Try it option, so just make use of it and enjoy your learning. Local Environment Setup If you are still willing to set up your environment for Node.js, this section will guide you. Node.js can be installed on different OS platforms such as Windows, Linux, Mac OS X, etc. You need the following tools on your computer − The Node.js binary installer Node Package Manager (NPM) IDE or Text Editor Binaries for various OS platforms are available on the downloads page of the official website of Node.js. Visit https://nodejs.org/en/downloadto get the list. This page shows two sets of binaries for different OS platforms, one for the current or latest version, and the other a version with LTS (Long Term Support), that is recommended for a normal user. 32 bit and 64 bit installers as well as ZIP archives for Windows, macOS installer as well as tar archives and binaries for Linux OS on x64 and ARM architecture are available. Installation on Windows Assuming that you are working with Windows 10/Windows 11 powered computer, download the 64-bit installer for Windows: https://nodejs.org/dist/v20.9.0/node-v20.9.0-x64.msi, and start the installation b double-clicking the downloaded file. The installation takes you through a few steps of the installation wizard. It also adds the installation directory of Node.js executable to the system path. To verify if Node.js has been successfully installed, open the command prompt and type node -v. If Node.js is installed successfully then it will display the version of the Node.js installed on your machine, as shown below. Installation on Ubuntu Linux First, download the tar file corresponding to Linux binary (https://nodejs.org/dist/v20.9.0/node-v20.9.0-linux-x64.tar.xz) and then, extract the binary using the tar command − tar -xf node-v20.9.0-linux-x64.tar.gz Move the extracted files to the installation directory /usr/local/node-v20.9.0. sudo mv node-<version> /usr/local/node-v20.9.0 Create a symlink to the executable in /usr/bin directory. sudo ln -s /usr/local/node-v20.9.0/bin/node /usr/bin/node You can now verify the correct installation with the following command − node -v Using Ubuntu package manager Refresh your local package index first by the following command − sudo apt update Then install Node.js − sudo apt install nodejs As in above case, verify the installation node -v NPM (Node Package Manager) is included in Node.js binaries from its official website since Node version 0.6.0., so you are not required to install it separately. You can use any text editor available in your OS (notepad in Windows, vi or nano in Ubuntu) to key-in and save the Node.js script. However, it is recommended that you use a suitable IDE for the purpose as it has several features such as syntax highlighting etc. VS Code is a popular source-code editor, which has out of the box support for JavaScript (and hence Node.js), which is highly recommended. Print Page Previous Next Advertisements ”;

Node.js – First Application

Node.js – First Application ”; Previous Next When learning a new language or a framework, the first application to write is a Hello World program. Such a program displays the Hello World message. This illustrates the basic syntax of the language and also serves to test whether the installation of the language compiler has been correctly done or not. In this chapter, we shall write a Hello World application in Node.js. Console Application Node.js has a command-line interface. Node.js runtime also allows you to execute JavaScript code outside the browser. Hence, any JavaScript code can be run in a command terminal with Node.js executable. Save the following single line JavaScript as hello.js file. console.log(“Hello World”); Open a powershell (or command prompt) terminal in the folder in which hello.js file is present, and enter the following command − PS D:nodejs> node hello.js Hello World The Hello World message is displayed in the terminal. Creating Node.js Application To create a “Hello, World!” web application using Node.js, you need the following three important components − Import required modules − We use the require directive to load Node.js modules. Create server − A server which will listen to client”s requests similar to Apache HTTP Server. Read request and return response − The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response. Step 1 – Import Required Module We use the require directive to load the http module and store the returned HTTP instance into an http variable as follows − var http = require(“http”); Step 2 – Create Server We use the created http instance and call http.createServer() method to create a server instance and then we bind it at port 3000 using the listen method associated with the server instance. Pass it a function with parameters request and response. The createserver() method has the following syntax − http.createServer(requestListener); The requestlistener parameter is a function that executes whenever the server receives a request from the client. This function processes the incoming request and forms a server reponse. The requestlistener function takes request HTTP request and response objects from Node.js runtime, and returns a ServerResponse object. listener = function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {”Content-Type”: ”text/html”}); // Send the response body as “Hello World” response.end(”<h2 style=”text-align: center;”>Hello World</h2>”); }; The above function adds the status code and content-type headers to the ServerResponse, and Hello World message. This function is used as a parameter to createserver() method. The server is made to listen for the incoming request at a particular port (let us assign 3000 as the port). Step 3 – Testing Request & Response Write the sample implementation to always return “Hello World”. Save the following script as hello.js. http = require(”node:http”); listener = function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/html response.writeHead(200, {”Content-Type”: ”text/html”}); // Send the response body as “Hello World” response.end(”<h2 style=”text-align: center;”>Hello World</h2>”); }; server = http.createServer(listener); server.listen(3000); // Console will print the message console.log(”Server running at http://127.0.0.1:3000/”); In the PowerShell terminal, enter the following command. PS D:nodejs> node hello.js Server running at http://127.0.0.1:3000/ The program starts the Node.js server on the localhost, and goes in the listen mode at port 3000. Now open a browser, and enter http://127.0.0.1:3000/ as the URL. The browser displays the Hello World message as desired. Print Page Previous Next Advertisements ”;