简体   繁体   中英

Require express in one file and use express.static in another

How would I use express in one file, in other files that need to use the express package also. Currently I have a file server.js, that has the

var express = require('express');
var app = express();

I want to use express in my other files that are in different directories, how would I do this without doing a require?

Updated question


How would I pass 'var express = require('express');' to another file so that I can use express.static?

If you don't want to use require you can pass app like this:

app.js

var express = require('express');
var app = express();
var something = require('./something')(app);

something.js

module.exports = function (app) {
  // do something with app
};

You can use module.exports to assign app variable , which can be used imported/required my other file . Sample example like below

a.js

var express = require('express');
var app = express();
module.exports.app = app;

b.js

var a = require('./a');
a.app.listen(3000,function(){
 console.log("Server Is up and running");
});

In nodeJs different files that we have in our application are treated as different module, so when we want to use them we export them and use them, here express is a package we are using so you can define it one file and export that file and require it in another file. use module.exports and require it another file.

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