Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [app.js]
- const http = require('http');
- const fs = require('fs');
- const db = require('./db');
- const hostname = '127.0.0.1';
- const port = 3000;
- const server = http.createServer((req,res) => {
- res.statusCode = 200;
- res.setHeader('Content-type','text/html');
- res.write('your domain is '+ hostname);
- res.end();
- });
- server.listen(port, hostname, () => {
- console.log('this project is at '+ port + ' and hostname is '+ hostname);
- // this is called a 'callback pattern'
- var callback = function(err, data) {
- if(err) throw err;
- else console.log(data);
- };
- // note how the callback is the last argument passed to the function
- db.statement('SELECT * FROM draft_tbl where id = 3', callback);
- });
- [db.js]
- // move this outside of your function because you don't need to recreate the
- // connection each time you run a query
- const mysql = require('mysql');
- var con = mysql.createConnection({
- host: "127.0.0.1",
- user: "root",
- password: "",
- database: "mydbname"
- });
- // and run this immediately because you want to know if it fails *before* you
- // run any queries
- con.connect(function(err) {
- if (err) throw err;
- else console.log("Actually db is connected!");
- });
- var statement = function (query_arg, done) {
- // this function also uses a callback, which is a sign that the function is
- // asynchronous
- con.query(query_arg, function (error, rows, fields) {
- if (error){
- done(error);
- } else {
- console.log(rows); // this console.log working directly. show true result of query
- // here we call the "callback" with the rows returned as the second argument
- done(null, rows);
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement