导出其他函数中的函数

Exporting the function which is inside an other function

当服务器启动时,我正在调用一个函数:

server.listen(port, someFunction());

在该函数内部,我执行了一些异步操作来填充对象内部的数据。

我想与其他文件共享该对象中填充的任何数据。

someFunction(){
  someObject={
    //this gets populated with some asynchronous operation.
  }
  functionInsideFunction(){
   //I want this function to return someObject of the parent function
  }
 //This function can't return anything because it shows error, as this is 
  // being invoked at the server start.
}

我想导出 functionInsideFunction 以便我可以在其他文件中获取存储在 someFunction 中的 someData!

那么我的方法应该是什么!?

Server.listen 期待回调函数,但 someFunction 似乎 return 没有人。

您可以在 someFunction 中执行 server.listen(port, someFunction.functionInsideFunction);return functionInsideFunction() {}

你也可以这样做:

const http = require('http')
// create your global object
let myObj = { }


var requestListener = function (req, res) {
  // use the object
  console.log(myObj);
  res.writeHead(200);
  res.end('Hello, World!');
}

var server = http.createServer(requestListener);
server.listen(3000, function() { 
  console.log("Listening on port 3000")
  // fill the object here
  myObj = {
    'name': 'hello'
  };
});