Node.js将parameter passing给express.js / passport.js中的require函数? 理解为什么?

嗨,大家好,我需要一些帮助理解node.js语法。 该应用程序已经把参数放在一个require函数上,它需要一个到另一个文件(而不是一个模块)的path。 让我给你一个我正在谈论的语法的例子,它位于名为server.js的主JavaScript文件上。

require('./config/passport')(passport); 

 require('./app/routes.js')(app, passport); 

我需要知道为什么这些“应用程序”和“护照”parameter passing给我的要求function。 应用程序是快递,护照是护照模块。

下面是完整的相关文件。 干杯

 var express = require('express'); var app = express(); var port = process.env.PORT || 8080; var mongoose = require('mongoose'); var passport = require('passport'); var flash = require('connect-flash'); require('./app/models/user'); var morgan = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var session = require('express-session'); var configDB = require('./config/database.js'); mongoose.connect(configDB.url); require('./config/passport')(passport); app.use(morgan('dev')); //http request logger app.use(cookieParser()); //reads cookies (needed for authentication) app.use(bodyParser()); //gets information from html forms app.set('view engine', 'ejs'); //required for passport app.use(session({secret: 'jonathanisawesome'})); app.use(passport.initialize()); app.use(passport.session()); //persistent login sessions app.use(flash()); //connect-flash for flash messages stored in sessions //routes require('./app/routes.js')(app, passport); //loads our routes and passes in our app and fully configured passport app.listen(port); console.log('the magix happens on port ' + port); 

 app.get('/logout', function(req,res){ req.logout(); res.redirect('/'); }); //processing of the form app.post('/login', passport.authenticate('local-login', { successRedirect: '/profile', failureRedirect: '/login', failureFlash : true })); app.post('/signup', passport.authenticate('local-signup', { successRedirect: '/profile', failureRedirect: '/signup', failureFlash : true })); // route for facebook authentication and login app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' })); // handle the callback after facebook has authenticated the user app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect : '/profile', failureRedirect : '/' })); app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] })); // the callback after google has authenticated the user app.get('/auth/google/callback', passport.authenticate('google', { successRedirect : '/profile', failureRedirect : '/' })); }; //route middleware to make sure a user is logged in function isLoggedIn(req,res,next){ //if user is authenticated in the session, carry on if(req.isAuthenticated()) return next(); //if they are not, redirect them to the homepage res.redirect('/'); }; 

 var LocalStrategy = require('passport-local').Strategy; var FacebookStrategy = require('passport-facebook').Strategy; var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy; var User = require('mongoose').model('User'); var configAuth = require('./auth'); var crypto = require('crypto'); module.exports = function(passport){ //passport session setup //persistent login sessions //passport needs ability to serialize and unserialize users out of sessions //use to serialize the user for the session passport.serializeUser(function(user,done){ done(null, user.id); }); //deserialize user passport.deserializeUser(function(id,done){ User.findById(id, function(err, user){ done(err, user); }); }); //local signup //using named strategies one for login and one for signup //by default if there was no name it would be called 'local' passport.use('local-signup', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : 'email', passwordField : 'password', passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, email, password, done) { // asynchronous // User.findOne wont fire unless data is sent back process.nextTick(function() { // create the user var newUser = new User(); // set the user's local credentials newUser.email = email; newUser.password = password; //password is hashed on the model layer // save the user newUser.save(function(err,user) { if(err || !user){ //error handling if(err.code===11000){ //email taken return done(null, false, req.flash('signupMessage', 'Sorry, the email '+newUser.email+' has been taken')); }else{ //its a hacker return done(null, false, req.flash('signupMessage', JSON.stringify(err))); } }else{ return done(null, newUser); } }); }); })); passport.use('local-login', new LocalStrategy({ // by default, local strategy uses username and password, we will override with email usernameField : 'email', passwordField : 'password', passReqToCallback : true // allows us to pass back the entire request to the callback }, function(req, email, password, done) { // callback with email and password from our form // find a user whose email is the same as the forms email // we are checking to see if the user trying to login already exists User.findOne({ 'email' : email }, function(err, user) { // if there are any errors, return the error before anything else if (err) return done(err); // if no user is found, return the message if (!user) return done(null, false, req.flash('loginMessage', 'No user found.')); // req.flash is the way to set flashdata using connect-flash // if the user is found but the password is wrong if (!user.authenticate(password)) return done(null, false, req.flash('loginMessage', 'Oops! Wrong password.')); // create the loginMessage and save it to session as flashdata // all is well, return successful user return done(null, user); }); })); //facebook passport.use(new FacebookStrategy({ clientID: configAuth.facebookAuth.clientID, clientSecret: configAuth.facebookAuth.clientSecret, callbackURL: configAuth.facebookAuth.callbackURL }, function(accessToken, refreshToken, profile, done) { process.nextTick(function(){ User.findOne({'facebook.id': profile.id}, function(err, user){ if(err) return done(err); if(user) return done(null, user); else { var newUser = new User(); newUser.email = profile.emails[0].value; newUser.password = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64'); newUser.socialLogin.facebook.id = profile.id; newUser.socialLogin.facebook.token = accessToken; newUser.socialLogin.facebook.name = profile.name.givenName + ' ' + profile.name.familyName; newUser.socialLogin.facebook.email = profile.emails[0].value; newUser.save(function(err){ if(err) console.log(err) return done(null, newUser); }) console.log(profile); } }); }); } )); passport.use(new GoogleStrategy({ clientID : configAuth.googleAuth.clientID, clientSecret : configAuth.googleAuth.clientSecret, callbackURL : configAuth.googleAuth.callbackURL, }, function(token, refreshToken, profile, done) { // make the code asynchronous // User.findOne won't fire until we have all our data back from Google process.nextTick(function() { // try to find the user based on their google id User.findOne({ 'google.id' : profile.id }, function(err, user) { if (err) return done(err); if (user) { // if a user is found, log them in return done(null, user); } else { // if the user isnt in our database, create a new user var newUser = new User(); newUser.email = profile.emails[0].value; newUser.password = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64'); newUser.socialLogin.google.id = profile.id; newUser.socialLogin.google.token = token; newUser.socialLogin.google.name = profile.displayName; newUser.socialLogin.google.email = profile.emails[0].value; // pull the first email // save the user newUser.save(function(err) { if (err) throw err; return done(null, newUser); }); } }); }); })); }; 

以这个例子:

 var session = require('express-session'); var MongoStore = require('connect-mongo')(session); app.use(session({ secret: 'foo', store: new MongoStore(options) })); 

正如你所看到的MongoStore是为了与会话一起使用,所以它取决于该模块。

这个:

 require('./config/passport')(passport); 

大致相当于这个:

 var pp = require('./config/passport'); pp(passport); 

为了解释, require('./config/passport')返回一个需要一个参数的函数。 您可以直接在上面的第一个表单中调用该函数,也可以将其分配给一个variables,然后调用它。

require('./config/passport')返回一个函数,期望passport作为它的参数。