如何在Node.js中创建一个模块文件

时间:2014-12-10 01:09:47

标签: javascript node.js

我想在一个文件中单独使用以下代码,然后在其他文件中调用它。对于exports.module,这是可能的,对吧?

var express = require('express');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var configAuth = require('./authentication');

var app = express();

function ensureAuthenticated(req, res, next) {
    console.log('isAuthenticated', req.isAuthenticated());
    if (req.isAuthenticated()) {
        return next();
    }
    res.send('not authenticated');
}

passport.use(new FacebookStrategy({
        clientID: configAuth.facebook.clientID,
        clientSecret: configAuth.facebook.clientSecret,
        callbackURL: configAuth.facebook.callbackURL
    },
    function(accessToken, refreshToken, profile, done) {
        process.nextTick(function() {
            return done(null, profile);
        });
    }
));

app.get('/auth/facebook', passport.authenticate('facebook'));

app.get('/auth/facebook/callback', passport.authenticate('facebook', {
        failureRedirect: '/'
    }),
    function(req, res) {
        res.redirect('facebook.com/celicoo');
});

我不知道如何打电话。

例如,我在authentication.js文件中有这个代码,我想在我的routes.js文件中调用它,我该怎么做?

1 个答案:

答案 0 :(得分:0)

如果没有看到你的目录结构,那么创建一个名为index.js的新文件,它应该只有一行:

module.exports = require('./app/yourapp');

其中yourapp是您在上面发布的文件,将该文件的内容放在您想要的任何目录中。通过运行'node index.js'

执行