gpt4 book ai didi

node.js - 使用 require 时丢失全局变量

转载 作者:太空宇宙 更新时间:2023-11-03 22:02:50 24 4
gpt4 key购买 nike

我正在尝试全局定义一些东西(下划线库, Mongoose ,数据库连接,最终是权限对象)

app.js

/* module dependencies */
const express = require('express');
const auth = require('http-auth');
const underscore = require('underscore');
const expressValidator = require('express-validator');
const mongo = require('mongodb');
const db = require('./library/db');
/*end module dependencies */


/*routes files*/
const post = require('./routes/post');
/* end route files */


/* start the app instance */
var app = express();


/* authentication */
var basic = auth({
authRealm : "Private area.",
authList : ['Shi:many222', 'Lota:123456']
});
/* end authentication*/


/* pass app as an argument to the use method */
app.configure(function () {
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(expressValidator);
app.use(db);
//app.use(underscore);
/* config debugging */
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
/* production instance */
app.configure('production', function(){
app.use(express.errorHandler());
});
/* end config debugging */
});


/* start route management */
app.get('/post', function(req, res) {
basic.apply(req, res, function(username) {
post.use(app);
post.findAll(req, res);
});
});
app.get('/post/:id', function(req, res) {
post.findById(req, res);
});


/* port management */
var port = 8000;
app.listen(port);
console.log('Listening: port: '+port);

post.js

    // Module dependencies
const underscore = require("underscore");


// placeholder for app instance
var app;


// add a use function to exports that we can access from our app
exports.use = function (appInstance) {
// make app instance available in post.js
app = appInstance;
};


/* find all rows */
exports.findAll = function(req, res) {
console.log('Post:findAll');
app.db.collection('Post', function(err, collection) {
collection.find({},{limit: 100}).toArray(function(err, items) {
res.send(exports.parseModels(items));
});
});
};


/* parse a single or all items passed to it for formatting */
exports.parseModels = function (items) {
underscore.each(items, function(key, val) {
console.log('underscore parsed an object');
});
return items;
};

db.js

var mongo = require('mongodb');

var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;

var server = new Server('localhost', 27017, {auto_reconnect: true});
var db = new Db('website', server);

db.open(function(err, db) {
if(!err) {
//do an error here
}
});

exports.db = db;

我在将数据库置于正确的范围内时遇到问题,目前当在 post.js 中调用查询时,我收到此错误:

    ost:findAll
TypeError: Cannot call method 'collection' of undefined
at Object.exports.findAll (/Github/-api-v3/routes/post.js:19:10)
at /Github/-api-v3/app.js:53:10
at Basic.apply (/Github/-api-v3/node_modules/http-auth/lib/auth/basic.js:48:4)
at /Github/-api-v3/app.js:51:9
at callbacks (/Github/-api-v3/node_modules/express/lib/router/index.js:161:37)
at param (/Github/-api-v3/node_modules/express/lib/router/index.js:135:11)
at pass (/Github/-api-v3/node_modules/express/lib/router/index.js:142:5)
at Router._dispatch (/Github/-api-v3/node_modules/express/lib/router/index.js:170:5)
at Object.router (/Github/-api-v3/node_modules/express/lib/router/index.js:33:10)
at next (/Github/-api-v3/node_modules/express/node_modules/connect/lib/proto.js:199:15)

最佳答案

每个模块都在具有自己作用域的闭包中运行。这意味着您定义的任何变量只能在该模块内访问。您想要使外部可见的任何方法或变量都应添加到 module.exports对象。

如果您确实必须定义全局变量,则需要将其作为属性添加到 global对象,但这应该保持在绝对最低限度。

正确的方法是在您使用的每个模块中要求任何依赖模块。所以你应该这样做var _ = require("underscore");post.js如果你想要_引用下划线。

如果您需要post.js了解您的app例如,您应该将其作为参数传递给 module.exports 中可用的函数。对象 post.js .

post.js

// Module dependencies
const _ = require("underscore");

// placeholder for app instance
var app;

// add a use function to exports that
// we can access from our app
exports.use = function (appInstance) {
// make app instance available in post.js
app = appInstance;
// app.db is also accessible
}

// add the rest of the methods here

app.js

// Module dependencies
const express = require('express');
const auth = require('http-auth');
const _ = require('underscore');
const expressValidator = require('express-validator');
const post = require('./routes/post');

// create app instance
var app = express();

// require db into app.db
app.db = require("./db");

// pass app as an argument to the use method
post.use(app);

注意:我更喜欢使用 const 来表示依赖关系,以便更容易与普通变量/实例区分开来。另请注意 exportsmodule.exports 的简写.

关于node.js - 使用 require 时丢失全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14220368/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com