繁体   English   中英

NodeJS中的exports语句

[英]The exports statement in NodeJS

我在server.js中有以下代码

var http = require('http');

function start() {
    function onRequest(request, response) {
        console.log('onrequest called');
        response.writeHead(200, { 'Content-type': 'text/plain' });
        response.write("Hello world!");
        response.end();
    }

    http.createServer(onRequest).listen(8888);
    console.log("Server started!");
}

exports.start = start;

以及index.js中的以下内容

var server = require('./server');
server.start();

我不理解的是exports.start = start; 正在工作。 exports来自哪里? 为什么index.js通过server.start();调用start方法server.start(); 而不是exports.start() exports不仅仅是我们放在全局命名空间中的变量,通过将其作为全局变量exports的属性来使其他模块可以访问本地变量吗?

救命!

Node将每个模块包装在它自己的IIFE ,提供诸如moduleexports__dirname等参数。

所以当你写:

var http = require('http');

function start() {
    function onRequest(request, response) {
        console.log('onrequest called');
        response.writeHead(200, { 'Content-type': 'text/plain' });
        response.write("Hello world!");
        response.end();
    }

    http.createServer(onRequest).listen(8888);
    console.log("Server started!");
}

exports.start = start;

它实际上包含在以下内容中:

(function(module, exports, __dirname, ...) {
  var http = require('http');

  function start() {
      function onRequest(request, response) {
          console.log('onrequest called');
          response.writeHead(200, { 'Content-type': 'text/plain' });
          response.write("Hello world!");
          response.end();
      }

      http.createServer(onRequest).listen(8888);
      console.log("Server started!");
  }

  exports.start = start;
})(module, exports, __dirname, ...)

我不理解的是exports.start = start行; 正在工作。 出口来自哪里?

exports就像任何其他JS对象一样是一个对象。 您正在附加一个对exports.start start的引用。

为什么index.js通过server.start()调用start方法; 而不是exports.start()?

好问题。 由于exports只是一个对象,因此除非您通过要求模块提供该引用,否则exports.start不会引用任何内容。

但是,如果您的目标是没有局部变量,则可以执行此操作。

require('./server').start()

暂无
暂无

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

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