简体   繁体   English

Node.js模块正确用法

[英]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{ ... }; 我编写的代码通常就像我没有进行导出一样,然后我用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 . 通常,您将看到运行快速服务器的server.js类型文件作为主要入口点程序,但没有提及module.exports They just have top-level code that executes when you run node server.js , which is fine. 它们只有运行node server.js时执行的顶级代码,这很好。

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. 那么你所拥有的是好的,但是我试着保持我的源代码部分与CommonJS扩展密切相关,我认为随着ECMAScript 6的采用,它将不再受欢迎,仅限于module.exports顶部的隔离require语句module.exports在文件中间module.exports底部的配置和纯JavaScript(没有CommonJS的东西)。 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. 它是等价的,在我看来只是有点整洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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