简体   繁体   中英

Node.js Module Correct Usage

I wanted to make sure I am following a normal convention when I used modules.

I wrote code normally like I would if I wasnt making an export, then I wrap the whole file with module.exports{ ... }; .
It works, but I just want to make sure I am not doing something that would get me fired. It feels too simple to be correct... Am I over thinking it?

module.exports=function() {

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

    app.use(express.static(__dirname+'/root'));


    var clientCount=0, currentid=0;
    var players=new Array();


    app.get('/login/*', function(request, response) {
        ...
    }

    ...

}

In your example it looks like you are exporting a single function, which looks like an express server. Since that module in your snippet doesn't export anything, there's no need for a wrapper function. Commonly you will see server.js type files that run an express server as main entrypoint programs that don't have any mention of module.exports . They just have top-level code that executes when you run node server.js , which is fine.

If for some reason you want to be able to have a separate module require this module and start it with a function call, like:

var server = require('./server');
server(); //call the function to start the express server

Then what you have is OK, but I try to keep the portion of my source code intimately tied to the CommonJS extensions, which I believe will fall out of favor as ECMAScript 6 gains adoption, limited to isolated require statements at the top with module.exports configuration at the bottom and just pure JavaScript (no CommonJS stuff) in the middle of the file. I prefer this pattern:

//CommonJS require statements
var express = require('express')();

//main module body code. Pure JS. No CommonJS pollution.
function setup() {
  ...
}

//CommonJS exports stuff
module.exports = setup;

It's equivalent, just a bit neater in my opinion.

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