Advertisement
Guest User

Untitled

a guest
Jan 13th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. [app.js]
  2. const http = require('http');
  3. const fs = require('fs');
  4. const db = require('./db');
  5.  
  6. const hostname = '127.0.0.1';
  7.  
  8. const port = 3000;
  9.  
  10. const server = http.createServer((req,res) => {
  11. res.statusCode = 200;
  12. res.setHeader('Content-type','text/html');
  13. res.write('your domain is '+ hostname);
  14. res.end();
  15. });
  16.  
  17. server.listen(port, hostname, () => {
  18. console.log('this project is at '+ port + ' and hostname is '+ hostname);
  19.  
  20.  
  21. // this is called a 'callback pattern'
  22. var callback = function(err, data) {
  23. if(err) throw err;
  24. else console.log(data);
  25. };
  26.  
  27. // note how the callback is the last argument passed to the function
  28. db.statement('SELECT * FROM draft_tbl where id = 3', callback);
  29.  
  30. });
  31.  
  32. [db.js]
  33.  
  34. // move this outside of your function because you don't need to recreate the
  35. // connection each time you run a query
  36. const mysql = require('mysql');
  37. var con = mysql.createConnection({
  38. host: "127.0.0.1",
  39. user: "root",
  40. password: "",
  41. database: "mydbname"
  42. });
  43.  
  44. // and run this immediately because you want to know if it fails *before* you
  45. // run any queries
  46. con.connect(function(err) {
  47. if (err) throw err;
  48. else console.log("Actually db is connected!");
  49. });
  50.  
  51. var statement = function (query_arg, done) {
  52.  
  53. // this function also uses a callback, which is a sign that the function is
  54. // asynchronous
  55. con.query(query_arg, function (error, rows, fields) {
  56. if (error){
  57. done(error);
  58. } else {
  59.  
  60. console.log(rows); // this console.log working directly. show true result of query
  61.  
  62. // here we call the "callback" with the rows returned as the second argument
  63. done(null, rows);
  64. }
  65. });
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement