NodeJS过程执行流程

时间:2017-02-11 16:02:51

标签: node.js

我是Nodejs的新手,并且来自程序语言背景,所以我需要知道我的代码的执行流程。我有一个关于Nodejs程序流程的一般性问题。这是场景:

代码结构:

authenticator

问题涉及数据库。由于数据库连接不在app.js文件中,而是在模型文件夹中的.js文件中,在什么时候进行数据库连接?并且是每次进行数据库查询时建立的连接吗?

我希望发生的事情是,数据库连接会进行一次并保持连接,直到应用程序终止。我尝试将数据库连接放在app.js中,但是当我尝试数据库查询时出现错误,所以我必须将数据库连接放在与数据库查询相同的文件中......不知怎的,这对我来说似乎不对。谁能解释节点如何处理这种流程?....将会感激任何帮助。

编辑:这是代码的样本

app.js

 Appnamefolder
   ...standard node folders(.idea,css,fonts,etc)
   ...model 
   ....database.js (connect to db and execute db queries)
   ...public
   ...routes
   ....users.js (GET and POST procedures....calls db queries via module.export)
   ...views
   ...app.js
   ...other js files

loaddealertable.js

var express = require('express');
var path=require('path');
var bodyParser = require('body-parser');
var cookieParser=require('cookie-parser');
var expressSession=require('express-session');
var expejs = require('ejs');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var expressSession = require('express-session');
var expressLayouts=require("express-ejs-layouts") // add this requirement
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var crypto = require("crypto");
var loaddealerTable=require('./loaddealerTable');


//var neo4j = require('neo4j-driver').v1;
// var neo4jdb = neo4j.driver("bolt://localhost:7474", neo4j.auth.basic("neo4j", "password"),
//   {
//            trust: "TRUST_ON_FIRST_USE",
//        encrypted:true
//   });
//***************Notifications Permission*******


var routes = require('./routes/index');
var users = require('./routes/users');

var csocket=require('./socketconnections');

var app=express();
var server=require('http').createServer(app);
sockets = require('./socketserver');
//rpaMessageWaiting = require('./getRPAmessages');

//var io=require('socket.io').listen(server);


// View Engine
app.set('views', path.join(__dirname,'views'));
app.set('view options', { layout:'layout.ejs' });
app.set('view engine','ejs');

//bodyParsers middleware
app.use(bodyParser.json());  
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

app.use(expressLayouts);

//set up public folder
app.use(express.static(path.join(__dirname, '/public')));

// set express session with secret
app.use(expressSession({ secret: process.env.SESSION_SECRET || 'secret',
                        resave: true,
                        saveUninitialized: true

                        }));
// Passport initialization
app.use(passport.initialize());
app.use(passport.session());


//Express Validitor...validate inputs..taken from github middleware options

app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));


// connect flash middleware
app.use(flash());

// set global variables for flash messages
app.use(function (req, res, next)
    {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
  res.locals.user = req.user || null;
    next();
    });

// Middelware for route files

app.use('/', routes);
app.use('/users', users);   //need to check routing
sockets.startSocketServer(server);
//load dealer table
  console.log("load dealer table");
 **loaddealerTable();    //First call on the DB**



 //============socket io listening=======================
      app.set('port',(process.env.PORT|| 3000));
      server.listen(app.get('port'), function() 
      {
       console.log('Server started on port '+app.get('port')); 
     // console.log('Server started on port .....');
        // app.get('/index',function (req,res) {
       //  // body...
       // res.render(__dirname+'/index');

       });

user.js的

var loaddealerTable=function()
  {
    var memorytbl=require('./memorytables');
    var User = require('./model/user');
    var getHashKey=require('./gethashkey');
    const hashMax=1000;
    console.log("call get dealers from DB");
    User.getallDealers(function(err,dealerFound,result)
     {
      if (dealerFound)
       {
       //       

       for (i=0; i< result.records.length; i++)
       {

        memorytbl.Dealer.email      =result.records[i].get(0).properties.email;
        memorytbl.Dealer.name       =result.records[i].get(0).properties.name;
        memorytbl.Dealer.telephone  =result.records[i].get(0).properties.storenumber;
        memorytbl.Dealer.creditcard =result.records[i].get(0).properties.creditcard;
        memorytbl.Dealer.delivery   =result.records[i].get(0).properties.delivery;
        memorytbl.Dealer.location   =result.records[i].get(0).properties.location;
        memorytbl.Dealer.rating     =result.records[i].get(0).properties.rating;

        var hashIndex = getHashKey(memorytbl.Dealer.email ,hashMax);
        memorytbl.DealersQ[hashIndex]=memorytbl.Dealer;



       } //end of for i

      }  //end of if....
      else
       { 
        console.log("No dealers found....table is empty");
       }
     }) //end of loaddealers table db call


   } //end of load dealers table function
  module.exports=loaddealerTable;

1 个答案:

答案 0 :(得分:1)

首先,您必须了解每个文件都是module

您的应用程序首先运行单个js文件(模块),如node app.js

一个模块可以加载另一个模块而另一个模块等等。 您的文件夹结构本身对订单没有任何影响。这一切都取决于您的代码以及加载模块的顺序。虽然您的同步代码将按照您编写的顺序运行,但您的异步代码将在未来运行,您需要了解event loop以了解代码中发生的情况。

从你提供的小上下文中我猜你可能会在连接它之前尝试查询你的数据库。我没有看到你的代码,但无论你在哪里连接(app.js文件或其他)都可能发生。