如何从文件中导出字符串并在NODE.js中的另一个文件上要求导出的字符串?

时间:2014-11-11 20:53:43

标签: javascript node.js express passport.js circular-dependency

我的目录结构如下:

collegesapp
├── node_modules
│   ├── express
│   ├── connect
│   ├── jade
│   └── passport
├── routes
│   └── routes.js
├── views
│   ├── index.jade
│   └── signin.jade
├── app.js
└── package.json
exports.serialized_user = serialized_user; //in app.js file *The variable serialized_user returns "Alex"

var serialized_user = require('../app.js').serialized_user; //in routes.js file

因此,当我将console.log(typeof(serialized_user))添加到我的routes.js文件并运行该应用程序时,我最终会在控制台中看到undefined而不是"string",当我添加{时{1}}到我的console.log(serialized_user)文件并运行应用程序,我最终在控制台中看不到任何内容而不是routes.js

您认为我的问题是什么?提前谢谢你:)

这是我的整个应用程序:

// app.js file

var express = require('express');

"Alex"

// routes.js

var connect = require('connect');
var passport = require('passport');
var localStrategy = require('passport-local').Strategy;
var mongoose = require('mongoose');
var mongodb = require('mongodb');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');;
var serveStatic = require('serve-static');
var errorHandler = require('errorhandler');
var routes = require('./routes/routes.js');
var user_model = require('./models/user_model.js');
var app = express();

//configuration
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(methodOverride());
app.use(express.Router());
app.use(serveStatic(__dirname + '/public_assets'));
app.use(passport.initialize());
app.use(passport.session());

if('development' == app.get('env')){
    app.use(errorHandler({dumpExceptions:true,showStack:true}));
}
if('production' == app.get('env')){
    app.use(errorHandler());
}

//user authentication on sign in
passport.use('signin_local_strategy', new localStrategy(
    function(username,password,done){
        user_model.findOne({username: username}, function(err, user){
            if(err)
                {
                    return(done(err));
                }
            if(!user)
                {
                    return(done(null,false));
                }
            if(user.password != password)
                {
                    return(done(null,false));
                }

            return(done(null,user));
        });
    }
));
var serialized_username;
passport.serializeUser(function(user, done){
    done(null, user.id);
    serialized_user = user.username;
    console.log(serialized_user);   //<<--- returns "Alex"
    console.log(typeof(serialized_user)); //<<--- returns string
});

exports.serialized_user = serialized_user;

passport.deserializeUser(function(done,user){
    user_model.findById(function(id, err){
        done(err,user);
    })
});


//routes
app.get('/', routes.indexResponseHandler);
app.get('/signin', routes.signinResponseHandler);
app.get('/signup', routes.signupResponseHandler);
app.get('/profile', routes.userProfileResponseHandler);
app.get('/failure', routes.signinErrorResponseHandler);
app.post('/signin',
    passport.authenticate('signin_local_strategy', { successRedirect:'/profile', 
                                                     failureRedirect: '/failure'})
    );
app.get('/db', routes.dbQuery);

app.listen(3000);

// user_models.js

var user_model = require('../models/user_model.js');

var serialized_user = require('../app.js').serialized_user;


exports.indexResponseHandler = function (req, res){
    res.render('index', {title: "College Clubs MN"});
}

exports.signinResponseHandler = function (req, res){
    res.render('signin', {title:"College Clubs MN | Sign in"});
}

exports.signupResponseHandler = function(req, res){
    res.render('signup', {title: "College Clubs MN | Sign Up"});
}

exports.userProfileResponseHandler = function(req, res){
    console.log(typeof((serialized_user))); //logs undefined but was supposed to logstring 
    res.send(typeof((serialized_user))); //<<-- shows undefined but was supposed to return string 
}

exports.signinErrorResponseHandler = function(req, res){
    res.send("Faild to Sign in ! :(");
}

2 个答案:

答案 0 :(得分:0)

在app.js中:

module.exports = {
    'serialized_user': serialized_user
};

并使用

访问它
var serialized_user = require('../app.js')
console.log(serialized_user.serialized_user):

也许看看这个: http://www.sitepoint.com/understanding-module-exports-exports-node-js/

答案 1 :(得分:0)

@clto,

// app.js

现在我将console.log(serialized_user)添加到passport的serializeUser方法的第一个参数的函数中。

这看起来像以下,控制台说出字符串“Alex”:

var serialized_username;
passport.serializeUser(function(user, done){
    done(null, user.id);
    serialized_user = user.username;
    console.log(serialized_user);   //<<--- returns "Alex"
    console.log(typeof(serialized_user)); //<<--- returns string
});

然后我在passport.serializeUser(...)之外添加了一个console.log(serialized_user),它是以下代码的最后一行,它返回undefined。

var serialized_username;
passport.serializeUser(function(user, done){
    done(null, user.id);
    serialized_user = user.username;
    console.log(serialized_user);   //<<--- returns "Alex"
    console.log(typeof(serialized_user)); //<<--- returns string
});
console.log((serialized_user)); //<<--- returns undefined 

这个错误是否与Node的执行方式(同步和异步)有关,可能吗?