English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Node.js Example:We will useNode.jsTo introduce the basics, examples of fs module, mysql module, http module, url module, parsing JSON, etc.
Below is the list of Node.js examples we will introduce in this Node.js tutorial:
Module/Topic | Examples |
Basics |
|
File System |
|
MySQL |
|
URL |
|
JSON |
|
HTTP |
|
Here is a simpleNode.js example,Used to print messages to the console
console.log("Hi there! This is Node.js!")
Calculator.js
// Returns the sum of two numbers exports.add = function(a, b) { return a+b; }; // Returns the difference between two numbers exports.subtract = function(a, b) { return a-b; }; // Returns the product of two numbers exports.multiply = function(a, b) { return a*b; };
var calculator = require('')/calculator') var a =10, b =5; console.log("Addition: ");+calculator.add(a, b)); console.log("Subtraction: ");+calculator.subtract(a, b)); console.log("Multiplication: ");+calculator.multiply(a, b));
readFileExample.js
// Import the file fs module var fs = require('fs'); var data = 'Learn Node FS module'; // The writeFile function with filename, content, and callback fs.writeFile('newfile.txt', data, function(err) { if (err) throw err; console.log('File is created successfully.'); });
Run the program using the node command at the terminal or command prompt:
Terminal output
$ node createFileExample.js File is created successfully.
This file should be created next to the example node.js program with the content 'Learning Node FS module'.
// Import the file system module var fs = require('fs'); // Read the file sample.html fs.readFile('sample.html', // Callback function called when the file reading is completed function(err, data) { if (err) throw err; // The data is a buffer containing the file content 8) });
Run the program using the node command at the terminal or command prompt:
Terminal output
$ node readFileExample.js <html> <body> <h1>Header</h/h1> <p>I have learnt to read a file in Node.js.</p>/p> </body> </html>
Ensure there is a file named 'sample.txt' next to the node.js example program.
// Import the fs module var fs = require('fs'); // Delete the file named 'sample.txt' fs.unlink('sample.txt', function(err) { if (err) throw err; // If there are no errors, the file has been successfully deleted console.log('File deleted!'); });
Run the program using the node command at the terminal or command prompt:
Terminal output
$ node deleteFile.js File deleted!
File has been successfully deleted.
In this example, we will write the content "Hello!” to the text file sample.txt.
// Import the file system module var fs = require('fs'); var data = "Hello !" // Write data to file sample.html fs.writeFile('sample.txt',data, // Callback function called after writing to the file function(err) { if (err) throw err; // If there is no error console.log("Data is written to file successfully.") });
When the above program is run in Terminal,
Program output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-write-to-file-example.js Data is written to file successfully.
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password" // corresponding password }); // Connect to the database. con.connect(function(err) { if (err) throw err; console.log("Connected!"); });
selectFromTable.js Simple example of MySQL SELECT FROM query
// Node.js MySQL SELECT FROM query example // import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Use the specified database }); // Establish a connection with the database. con.connect(function(err) { if (err) throw err; // If the connection is successful con.query("SELECT * FROM students", function (err, result, fields) { // If any error occurs while executing the above query, throw an error if (err) throw err; // If there are no errors, you will get the result console.log(result); }); });
selectFromWhere.js
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Use the specified database }); // Establish a connection with the database. con.connect(function(err) { if (err) throw err; // If the connection is successful con.query("SELECT * FROM students WHERE marks>90 // If any error occurs while executing the above query, throw an error if (err) throw err; // If there are no errors, you will get the result console.log(result); }); });
Open a terminal from the location of the above .js file, then run the selectFromWhere.js Node.js MySQL example program.
AscOrderExample.js
//import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Use the specified database }); // Establish a connection with the database. con.connect(function(err) { if (err) throw err; // If the connection is successful con.query("SELECT * FROM students ORDER BY marks // If any error occurs while executing the above query, throw an error if (err) throw err; // If there are no errors, you will get the result console.log(result); }); });
Run the above Node.js MySQL ORDER BY example program.
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Use the specified database }); // Establish a connection with the database. con.connect(function(err) { if (err) throw err; // If the connection is successful con.query("INSERT INTO students (name,rollno,marks) values ('Anisha',12,95function (err, result, fields) { // If any error occurs while executing the above query, throw an error if (err) throw err; // If there are no errors, you will get the result console.log(result); }); });
Run the Node.js MySQL program in the terminal above.
UpdateRecordsFiltered.js-Update records in MySQL table
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Use the specified database }); // Establish a connection with the database. con.connect(function(err) { if (err) throw err; // If the connection is successful con.query("UPDATE students SET marks=84 WHERE marks=74", function (err, result, fields) { // If any error occurs while executing the above query, throw an error if (err) throw err; // If there are no errors, you will get the result console.log(result); }); });
Run the above program in the terminal
Terminal output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node UpdateRecordsFiltered.js OkPacket { fieldCount: 0, affectedRows: 3, insertId: 0, serverStatus: 34, warningCount: 0, message: '(Rows matched: 3 Changed: 3 Warnings: 0', protocol41: true, changedRows: 3 }
Execute DELETE FROM query on the specified table when one or more properties on the table are filtered.
// import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Use the specified database }); // Connect to the database. con.connect(function(err) { if (err) throw err; // If the connection is successful con.query("DELETE FROM students WHERE rollno>"10", function (err, result, fields) { // If any error occurs while executing the above query, throw an error if (err) throw err; // If there are no errors, you will get the result console.log(result); }); });
Run deleteRecordsFiltered.js-Terminal output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node deleteRecordsFiltered.js OkPacket { fieldCount: 0, affectedRows: 6, insertId: 0, serverStatus: 34, warningCount: 0, message: '', protocol41: true, changedRows: 0}
We can use the DOT (.) operator to access records in the result set as arrays and as properties of records.
// Node.js MySQL result object example // import mysql module var mysql = require('mysql'); // create a connection variable with the required details var con = mysql.createConnection({ host: "localhost", // IP address of the server running mysql user: "arjun", // mysql database username password: "password", // corresponding password database: "studentsDB" // Use the specified database }); // Establish a connection with the database. con.connect(function(err) { if (err) throw err; // If the connection is successful con.query("SELECT * FROM students", function (err, result, fields) { // If any error occurs while executing the above query, throw an error if (err) throw err; // If there are no errors, you will get the result // Iterate over all rows in the result Object.keys(result).forEach(function(key) { var row = result[key]; console.log(row.name) }); }); });
Run the above program using the node in the terminal
Terminal output
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node selectUseResultObject.js John Arjun Prasanth Adarsh Raja Sai Ross Monica Lee Bruce Sukumar
// Import the url module var url = require('url'); var address = 'http://localhost:8080/index.php?type=page&action=update&id=5221"; var q = url.parse(address, true); console.log(q.host); //Returns 'localhost:8080 console.log(q.pathname); //Returns/index.php console.log(q.search); //returns '?type=page&action=update&id=5221" var qdata = q.query; // Returns an object: {Type: page, Operation: 'update', id = '"5221} console.log(qdata.type); //Returns "page" console.log(qdata.action); //Returns "update" console.log(qdata.id); //Returns " 5221"
Terminal output
$ node urlParsingExample.js localhost:8080 /index.php ?type=page&action=update&id=5221 page update 5221
The following examples can help you use the JSON.parse() function and access elements from the JSON object.
// JSON data var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}'; // Parse json var jsonParsed = JSON.parse(jsonData); // Access element console.log(jsonParsed.persons[0].name);
Run nodejs-parse-Terminal output of json.js
arjun@arjun-VPCEH26EN:~/workspace/nodejs$ node nodejs-parse-json.js John
Node.js Example – An HTTP Web Server that prepares responses with HTTP headers and messages.
// Import the http module in the file var http = require('http'); // Create a server http.createServer(function (req, res) { // HTTP headers // 200-Confirm message // To use html content for the response, "Content-Type" should be "text / html" res.writeHead(200, {'Content-Type': 'text/html'}); res.write('Node.js says hello!'); //Write a response to the client res.end(); //End of response }).listen(9000); //The server object is listening on port9000 is listening
Run the server
$ node httpWebServer.js
Open the browser and click the URL "http://127.0.0.1:9000/to trigger requests to our web server.