Node.js – Console ”; Previous Next A console is a text-based user interface that allows you to interact with the computer”s operating system or run code. With the console, you can write and execute commands or programs. It is also used for debugging and troubleshooting. The built-in library of Node.js includes the Console module. It provides functionality to print messages to IO streams, a functionality similar to the JavaScript console mechanism provided by web browsers. The Console module’s functionality has two major parts − Console class: The console class methods are console.log(), console.error() and console.warn() to display Node.js stream. global console object: A predefined object that echoes logging, errors and warning messages to the standard output stream. It is used without calling require(‘console’). The default usage of global console object is simple. The following code shows a typical usage of global console object to display logging, error and warning messages. Example // Welcome message console.log(”Welcome to Tutorialspoint!”); // Hello world message console.log(”hello world”); // printing to error stream console.error(new Error(”Oops… something went wrong”)); // print warning const name = ”NodeJS Tutorial”; console.warn(`Warning ${name}! Warning!`); Output Welcome to Tutorialspoint! hello world Error: Oops… something went wrong at Object.<anonymous> (D:nodejsemailappmain.js:11:15) at Module._compile (node:internal/modules/cjs/loader:1241:14) at Module._extensions..js (node:internal/modules/cjs/loader:1295:10) at Module.load (node:internal/modules/cjs/loader:1091:32) at Module._load (node:internal/modules/cjs/loader:938:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12) at node:internal/main/run_main_module:23:47 Warning NodeJS Tutorial! Warning! You can also customize the console object by designating the streams for reflecting the output and error logs. Declare an object of Console class and pass the stream objects as arguments. The program below redirects the logs and errors to the two disk files. const fs = require(”fs”); const out = fs.createWriteStream(”./stdout.log”); const err = fs.createWriteStream(”./stderr.log”); const logger = new console.Console(out, err); // Welcome message logger.log(”Welcome to Tutorialspoint!”); // Hello world message logger.log(”hello world”); // printing to error stream logger.error(new Error(”Oops… something went wrong”)); // print warning const name = ”NodeJS Tutorial”; logger.warn(`Warning ${name}! Warning!`); This will create two files stdout.log and stderr.log in the current directory, with the result of log(), error(), and warn() methods of console objects saved in them. Console Methods Following is a list of methods available with the console object. Sr.No. Method & Description 1 console.log([data][, …]) Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. 2 console.info([data][, …]) Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. 3 console.error([data][, …]) Prints to stderr with newline. This function can take multiple arguments in a printf()-like way. 4 console.warn([data][, …]) Prints to stderr with newline. This function can take multiple arguments in a printf()-like way 5 console.dir(obj[, options]) Uses util.inspect on obj and prints resulting string to stdout. 6 console.time(label) Mark a time. 7 console.timeEnd(label) Finish timer, record output. 8 console.trace(message[, …]) Print to stderr ”Trace :”, followed by the formatted message and stack trace to the current position. 9 console.assert(value[, message][, …]) Similar to assert.ok(), but the error message is formatted as util.format(message…). nodejs_global_objects.htm Print Page Previous Next Advertisements ”;
Category: Computer Programming
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 ”; 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 ”; 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 ”; 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 – 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 ”;
Node.js – Introduction
Node.js – Introduction ”; Previous Next What is Node.js? Node.js is a server-side runtime environment built on Google Chrome”s JavaScript Engine (V8 Engine). Node.js was developed by Ryan Dahl in 2009 and its latest version is v20.9.0. Node.js is a cross-platform (run on Windows, Linux, Unix, macOS, and more), open-source, back-end JavaScript runtime environment, that executes JavaScript code outside a web browser. The definition of Node.js as supplied by its official documentation is as follows − Node.js is a platform built on Chrome”s JavaScript runtime for easily building fast and scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices. Node.js environment is event-driven and provides non-blocking I/O, that optimizes throughput and scalability in web applications. The OpenJS Foundation, facilitated by the Linux Foundation”s Collaborative Projects program, now handles the Node.js distributed development. Features of Node.js Following are some of the important features that make Node.js the first choice of software architects. Asynchronous and Event Driven − All APIs of Node.js library are asynchronous, that is, non-blocking. It essentially means a Node.js based server never waits for an API to return data. The server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call. Very Fast − Being built on Google Chrome”s V8 JavaScript Engine, Node.js library is very fast in code execution. Single Threaded but Highly Scalable − Node.js uses a single threaded model with event looping. Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as opposed to traditional servers which create limited threads to handle requests. Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server. No Buffering − Node.js applications never buffer any data. These applications simply output the data in chunks. License − Node.js is released under the MIT license. The following diagram depicts some important parts of Node.js which we will discuss in detail in the subsequent chapters. Where to Use Node.js? Following are the areas where Node.js is proving itself as a perfect technology partner. I/O bound Applications Data Streaming Applications Data Intensive Real-time Applications (DIRT) JSON APIs based Applications Single Page Applications However, it is not advisable to use Node.js for CPU intensive applications. Node.js is primarily used to build network programs such as Web servers. However, you can build different types of applications such as command line applications, web applications, real-time chat applications, REST APIs etc. Thousands of open-source libraries for Node.js are available, most of them hosted on the npm website, npm is a package manager for the JavaScript programming language. A number web frameworks can be used to accelerate the development of applications. Some of the popular frameworks are Express.js, Feathers.js, Koa.js, Sails.js, Meteor, and many others. Number of IDEs such as Atom, JetBrains WebStorm, NetBeans, and Visual Studio Code support development of Node.js applications. Cloud-hosting platforms like Google Cloud Platform and AWS Elastic Beanstalk can be used to host Node.js applications. Print Page Previous Next Advertisements ”;