简体   繁体   中英

Node.js + Express passing an object

I'm building a small node.js/express project and have a function in configure.js that sets configuration options in my express app. For example:

server.js

var express = require('express');
var server = ('./configure');

var app = express();
server.configure(app);

configure.js

exports.configure = function(app) {
  app.set('title', 'Server');
};

This doesn't work but I hope it explains what I'm trying to do. I want to make changes to the app instance in server.js. How do I do this?

EDIT:

Okay I think i can get this all working if i understand why this isn't working. Is it to do with timing of the callback? The second console.log() isn't called.

configure.js

var fs = require('fs');

var StringDecoder = require('string_decoder').StringDecoder;
var decoder = new StringDecoder('utf8');


function configure(app) {

  var config = module.exports = {};

    fs.readFile('config.txt', function (err, data) {
      if (err) throw err;

      config.title = decoder.write(data)
      console.log(config.title)

    });

    if(config.title) console.log(config.title);
    //app.set('title', config.title)
}

module.exports = function (app) {
  configure(app);
};

server.js

var express = require('express');
var cfg = require('./configure');
var fs = require('fs');

var app = express()

cfg(app)

(config.txt is echo 'server' > config.txt)

What you have should actually work.

As for your question about using multiple functions, you can export and call each separately. This can be useful when timing is important (such as if other setup steps need to occur that aren't specified in configure.js ):

// configure.js

exports.configure = function (app) {
  // ...
};

exports.attachMiddlware = function (app) {
  // ...
};
// server.js

var express = require('express');
var server = require('./configure');

var app = express();
server.configure(app);
server.attachMiddlware(app);

You can also define a single entry function as the exported object which calls the functions needed within configure.js . This can possibly keep server.js cleaner by isolating the maintenance within configure.js :

function configure(app) {
  // ...
}

function attachMiddleware(app) {
  // ...
}

module.exports = function (app) {
  configure(app);
  attachMiddleware(app)
};
var express = require('express');
var configure = require('./configure');

var app = express();
configure(app);

I would avoid that and just do a json object:

app.js

var cfg = require('./config');
app.set('title', cfg.title);

config.js

var config = module.exports = {};
config.title = 'Server';

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