简体   繁体   中英

How make a file a module in Node.js

I want separate this code below in one file, and then call it in other file. This is possible with exports.module, right?

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');
});

I don't know how make this call.

For example, i have this code in the authentication.js file, and i want call it in my routes.js file, how can i do that?

Without seeing your directory structure and such make a new file called index.js and the only line it should have is:

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

where the yourapp is the file that you posted above, put the contents of that file in whatever directory you want. Execute by running 'node index.js'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM