-
Notifications
You must be signed in to change notification settings - Fork 1
/
01_connection.js
71 lines (59 loc) · 1.86 KB
/
01_connection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
{
"date_of_creation": "17 September 2017",
"aim_of_source": 'Testing database(mysql) connection in node.js',
"coded_by": 'Rishikesh Agrawani',
"output_img_links": "[
'0002mysql01connection2017-09-17at4.06.03PM.png',
'0003mysql01connection2017-09-17at4.07.51PM.png'
]"
}
*/
//Including http module
var http = require("http")
//Including mysql module(mysql node.js driver)
var mysql = require("mysql")
//Setting port
var port = 8080
//HTML text to display on the browser
var htmlText = "<center>"+
"<h1 style='color:green'> Connection established </h1>"+
"<a href='https://nodejs.org/en/'>Click here</a> to download"+
"</center>"
//HTML erro text to display on the browser
var htmlErrorText = "<center>"+
"<h1 style='color:red'> Error while creating db connection</h1>"+
"<a href='https://nodejs.org/en/'>Click here</a> to download"+
"</center>"
//Printing simple log message
console.log("Starting Node server")
//Creating server
server = http.createServer(
function(request, response){
//Creating connection object
var connection = mysql.createConnection({
host: "localhost",
"user": "rishikesh", //db username
"password": "rishikesh@321" //db password
})
//Creating and testing database connection
connection.connect(function(err){
if(err){
//Error
response.writeHead(500, {"Content-Type":"text/html"})
console.log("Error while creating connection")
response.end(htmlErrorText)
} else {
//Successful
response.writeHead(200, {"Content-Type":"text/html"})
console.log("Connection successful")
response.end(htmlText)
}
})
}
)
//Our http server should listen on port 8080
server.listen(port)
//Printing log messages
console.log("Server started which is listening on port 8080")
console.log("Visit at http://127.0.0.1:"+port)