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 ”;
Category: nodejs
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 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 – 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 – 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 ”;
Node.js – Home
Node.js Tutorial Table of content What is Node.js? Why Learn Node.js? How to Install Node.js? Applications of Node.js Example of Node.js Application Prerequisites to Learn Node.js Getting Started with Node.js Frequently Asked Questions on Node.js PDF Version Quick Guide Resources Job Search Discussion Node.js is a powerful JavaScript runtime environment, built on Google Chrome”s V8 JavaScript Engine. Node.js is open-source and cross platform. What is Node.js? Node.js is not a programming language like Python, Java or C/C++. Node.js is a runtime, similar to Java virtual machine, that converts JavaScript code into machine code. It is , widely used by thousands of developers around the world to develop I/O intensive web applications like video streaming sites, single-page applications, and other web applications. With Node.js, it is possible to use JavaScript as a backend. With JavaScript already being a popular choice for frontend development, application development around MERN (MongoDB, Express, React and Node.js.) and MEAN (MongoDB, Express, Angular and Node.js) stacks is being increasingly employed by developers. Why Learn Node.js? Node.js can be used to full fill multiple purpose like server-side programming, build APIs, etc. Node.js is used for server-side programming with JavaScript. Hence, you can use a single programming language (JavaScript) for both front-end and back-end development. Node.js implements asynchronous execution of tasks in a single thread with async and await technique. This makes Node.js application significantly faster than multi-threaded applications. Node.js is being used to build command line applications, web applications, real-time chat applications, REST APIs etc. How to Install Node.js? Different operating systems required different steps to install Node.js, please follow the provided methods according to your installed operating system. Node.js Installation on Windows Node.js Installation on Linux – Ubuntu Applications of Node.js Node.js is used for building different type of applications. Some of the application types are listed below. Streaming applications: Node.js can easily handle real-time data streams, where it is required to download resources on-demand without overloading the server or the user’s local machine. Node.js can also provide quick data synchronization between the server and the client, which improves user experience by minimizing delays using the Node.js event loop. Single page apps: Node.js is an excellent choice for SPAs because of its capability to efficiently handle asynchronous calls and heavy input/output(I/O) workloads. Data driven SPAs built with Express.js are fast, efficient and robust. Realtime applications: Node.js is ideal for building lightweight real-time applications, like messaging apps interfaces, chatbots etc. Node.js has an event- based architecture, as a result has an excellent WebSocket support. It facilitates real-time two-way communication between the server and the client. APIs: At the heart of Node.js is JavaScript. Hence, it becomes handling JSON data is easier. You can therefore build REST based APIs with Node.js. These are some of the use cases of Node.js. However, its usage is not restricted to these types. Companies are increasingly employing Node.js for variety of applications. Example of Node.js Application To create a basic Hello World application in Node.js, save the following single line JavaScript as hello.js file. console.log(“Hello World”); Open a powershell (or command prompt) terminal in the folder in which hello.js file is present, and enter the following command. The “Hello World” message is displayed in the terminal. PS D:nodejs> node hello.js Hello World To create a “Hello, World!” web application using Node.js, save the following code as hello.js: http = require(”node:http”); listener = function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/html response.writeHead(200, {”Content-Type”: ”text/html”}); // Send the response body as “Hello World” response.end(”<h2 style=”text-align: center;”>Hello World</h2>”); }; server = http.createServer(listener); server.listen(3000); // Console will print the message console.log(”Server running at http://127.0.0.1:3000/”); Run the above script from command line. C:nodejs> node hello.js Server running at http://127.0.0.1:3000/ The program starts the Node.js server on the localhost, and goes in the listen mode at port 3000. Now open a browser, and enter http://127.0.0.1:3000/ as the URL. The browser displays the Hello World message as desired. Prerequisites to Learn Node.js Before proceeding with this tutorial, you should have a basic understanding of JavaScript. As we are going to develop web-based applications using Node.js, it will be good if you have some understanding of other web technologies such as HTML, CSS, AJAX, etc. Getting Started with Node.js This tutorial is designed for software programmers who want to learn the Node.js and its architectural concepts from basics to advanced. This tutorial will give you enough understanding on all the necessary components of Node.js with suitable examples. Basics of Node.js Before going deep into nodejs you should familier with fundamentals of nodejs like environment setup, REPL terminal, NPM, Callbacks, Events, Objects, etc. Node.js Introduction Node.js Environment Setup Node.js First Application Node.js REPL Terminal Node.js Command Line Options Node.js Package Manager (NPM) Node.js Callbacks Concept Node.js Upload Files Node.js Send an Email Node.js Events Node.js Event Loop Node.js Event Emitter Node.js Debugger Node.js Global Objects Node.js Console Node.js Process Node.js File System Node.js Streams Node.js Scaling Application Node.js Packaging Node.js Modules Node.js modules provides a collection of functions that are used to perform different operations as per the requirements. All the improtant modules are listed below. Node.js Assert Module Node.js Buffer Module Node.js Console Module Node.js DNS Module Node.js OS Module Node.js Path Module Module Node.js Query String Tutorialspoint Node.js URL Tutorialspoint Node.js Utility Tutorialspoint Node.js V8 Tutorialspoint Node.js Jobs and Salary Node.js. is a popular tool for almost any kind of project. After Learning Node.js you can get job on different job profiles. Node.js Developer – Salary ranges in between ₹ 1.2 Lakhs to ₹ 12.6 Lakhs with an average annual salary of ₹ 5.7 Lakhs. Node.js Backend Developer – Salary ranges in between ₹ 1.2 Lakhs to ₹ 11.0 Lakhs with an average annual salary of ₹ 4.7 Lakhs. Frequently Asked Questions about Node.js Is Node.js Free to Use? Node.js is an open-source and cross-platform server framework. It is completely free to use on all the OS platforms – Windows, Linux, MacOS etc. Can Node.js
Node.js – NPM ”; Previous Next NPM − an acronym for Node Package Manager, refers to the Command line utility to install Node.js packages, perform version management and dependency management of Node.js packages. It also provides an online repository for node.js packages/modules which are searchable on https://www.npmjs.com/. A detailed documentation of NPM commands is also available on this link. If you are working with newer versions of Node.js (version 0.6.0 or later), the NPM utility is included with the Node.js binaries for all the OS platform bundles. Check the version of NPM in the command terminal − PS C:Usersmlath> npm -v 10.1.0 In case you have an older version of NPM, you need to update it to the latest version using the following command. npm install npm -g Note that YARN and PNPM tools are also available as alternatives for NPM. YARN installs packages more quickly and manage dependencies consistently across machines or in secure offline environments. PNPM (Performant NPM) is another fast and disk-space efficient package manager for Node.js packages. If your Node.js application depends on one or more external packages, they must be installed from NPM repository. NPM packages are installed in two modes either local or global. By default, a package is installed locally. Install Package Locally There is a simple syntax to install any Node.js module − npm install <Module Name> For example, following is the command to install a famous Node.js web framework module called express − npm install express Now you can use this module in your js file as following − var express = require(”express”); The local mode installation of a package refers to the package installation in node_modules directory lying in the folder where Node application is present. Locally deployed packages are accessible via require() method. Use –save at the end of the install command to add dependency entry into package.json of your application. The package.json file is a JSON file that is used to manage dependencies in Node.js projects. It contains information about the project, such as its name, version, and dependencies. The package.json file is used by the npm package manager to install and manage dependencies. The package.json file is typically located in the root directory of a Node.js project. It can be created by running the npm init command. Create a new folder for a new Node.js project, and run pnm init command inside it − PS D:nodejsnewnodeapp> npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. Press ^C at any time to quit. package name: (newnodeapp) newnodeapp version: (1.0.0) description: Test Node.js App entry point: (index.js) test command: git repository: keywords: test, nodejs author: mvl license: (ISC) About to write to D:nodejsNewNodeApppackage.json − { “name”: “newnodeapp”, “version”: “1.0.0”, “description”: “Test Node.js App”, “main”: “index.js”, “scripts”: { “test”: “echo “Error: no test specified” && exit 1″ }, “keywords”: [ “test”, “nodejs” ], “author”: “mvl”, “license”: “ISC” } Now, if we install express package into this package locally in this project, use the following command, it also adds dependency entry into the package.json. D:nodejsnewnodeapp>npm install express –save The package.json file in this folder will be updated to − { “name”: “newnodeapp”, “version”: “1.0.0”, “description”: “Test Node.js App”, “main”: “index.js”, “scripts”: { “test”: “echo “Error: no test specified” && exit 1″ }, “keywords”: [ “test”, “nodejs” ], “author”: “mvl”, “license”: “ISC”, “dependencies”: { “express”: “^4.18.2″ } } The express package code will be placed inside the node_modules subfolder of the package folder. If you have already placed all the project dependencies in your package.json file, all of them will be installed at once by simply running npm install (without any package name in front of it) You can also use -save-dev flag in the npm install command to add the package as DevDepndency. –save-dev installs and adds the entry to the package.json file devDependencies –no-save installs but does not add the entry to the package.json file dependencies –save-optional installs and adds the entry to the package.json file optionalDependencies –no-optional will prevent optional dependencies from being installed Shorthands of the flags can also be used − -S: –save -D: –save-dev -O: –save-optional The difference between devDependencies and dependencies is that the former contains development tools, like a testing library, while the latter is bundled with the app in production. Install Package Globally Globally installed packages/dependencies are stored in system directory. Such dependencies can be used in CLI (Command Line Interface) function of any node.js but cannot be imported using require() in Node application directly. Now let”s try installing the express module using global installation. npm install express -g This will produce a similar result but the module will be installed globally. On Linux, the global packages are placed in /usr/lib/node_modules folder, while for Windows, the path is C:Usersyour-usernameAppDataRoamingnpmnode_modules. Update Package To update the package installed locally in your Node.js project, open the command prompt or terminal in your project project folder and write the following update command. npm update <package name> The following command will update the existing ExpressJS module to the latest version. PS D:nodejsnewnodeapp> npm update express up to date, audited 63 packages in 2s 11 packages are looking for funding run `npm fund` for details found 0 vulnerabilities Uninstall Packages To uninstall a package from your project”s dependencies, use the following command to remove a local package from your project. npm uninstall <package name> The following command will uninstall ExpressJS from the application. PS D:nodejsnewnodeapp> npm uninstall express removed 62 packages, and audited 1 package in 603ms found 0 vulnerabilities The package entry will also be removed from the list of dependencies in the package.json file. Print Page Previous Next Advertisements ”;