Skip to content
Using a Database in NodeJs file:
-
Using node js we can able to use Database concept in js file.
-
But, for that we have to install some packages. (If you want to use Mysql in your code)
-
Before run your DB_nodejs.js , need to install some package’s (Ie: mysql, gently)
-
Open command prompt
- YOURPATH > rpm install mysql
- YOURPATH > rpm install gently
- Without above package’s we can’t able to run nodejs with DB related concept in nodejs.
- Refer Screen shot
Screen shot – 3
-
Installed packages are located in inside “node_modules” folder
Ex: D:\wamp\www\MYPATH\node_modules
-
If you can able to run above installation command in command prompt, better download it from net and keep it in “node_modules” folders.
-
Run your DB_node.js files in command prompt. (below is the sample code for DB_node.js, with sample Database Connectivity using nodejs)
-
10. Path is Cmd prompt:MYPATH>node DB_node.js, refer screen shot – 4
Screen shot – 4:
-
Now server is ready, then open browser run your file Ex: http://localhost:4020/
-
Once you run above URL in browser, you will get result in browser and also command prompt.
- Below is the sample Screen shot for Using DB in nodejs, refer screen shot – 5.
Screen shot – 5:
Code for DB_node.js:
var gently = new (require(‘gently’)); //Installed gently package path.
var sys = require(“sys”),
http = require(“http”),
url = require(“url”),
path = require(“path”),
fs = require(“fs”),
events = require(“events”);
// Create node.js server
http.createServer(function(request, response) {
// Require mysql plugin
var Client = require(‘mysql’).Client,
client = new Client();
// MYSQL username and password
client.user = ‘root’; //DB Username and password
client.password = ”;
//client.debug = true;
// Connect to the db
// do the mysql db stuffs
client.query(‘USE employee_master;’); //DB Name
client.query(‘SELECT * FROM employee_master WHERE empID=1’, //Sample Mysql Query
gently.expect(function selectCb(err, results, fields) {
if (err) {
throw err;
}
response.writeHeader(200, {“Content-Type”: “text/html”}); //If you use html tag in nodejs then use text/html”, if you use plain then “text/plain”
console.log(results);
response.write(‘<html><body>’);
response.write(‘<h1>Sample Product Listing In Node.js</h1>’);
if(results.length > 0)
{
for(var i=0; i<results.length; i++){
var firstResult = results[i];
response.write(‘<img src=”http://3.s3.envato.com/files/1581733/node-js-590x.png” width=”100px” height=”100px”>’)
response.write(‘<br />Employee Id: ‘ + firstResult[’empID’]);
response.write(‘<br />Employee Name: ‘ + firstResult[‘Name’]);
}
}
response.write(‘</body></html>’);
response.end();
client.end();
})
);
// this is the port the server listens on
}).listen(4020);