【问题标题】:Unable to export a function from a custom node.js module无法从自定义 node.js 模块导出函数
【发布时间】:2021-11-10 02:33:51
【问题描述】:

我正在测试一个简单的 node.js 自定义模块,该模块由 node.js 根目录中的 processTest.js 文件表示。这是它的内容:注意module.exports 包含一个函数processTest()

'use strict';

const { spawn } = require( 'child_process' );
const ls = spawn( 'ls', [ '-lh', '/usr' ] );

function runTest() {
  ls.stdout.on('data', (data) => {
    console.log(`stdout: ${data}`);
  });

  ls.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
  });

  ls.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
  });
}
module.exports = runTest;

node.js 主脚本中,我们尝试如下调用它:

const processTest = require("./processTest")

...

http.createServer(app).listen(port, '0.0.0.0', function () {
  console.debug(`HTTP: Listening on ${port} ..`)
  processTest.runTest();
})

但是我们得到了错误

未捕获的类型错误:processTest.runTest 不是函数

请注意,processTest 模块实际上是存在的,并且该功能是可见的。

这里出了什么问题,应该如何纠正?

【问题讨论】:

  • 改用processTest()
  • processTest() 不起作用 - 我需要更改模块导出,如 [即将] 接受的答案所示

标签: javascript module.exports


【解决方案1】:

您指的是processTest 文件中的函数。 (module.exports = runTest)。使用require("./processTest")()

或者只是将module.exports 更改为

module.exports = {
    runTest
}

require("./processTest").runTest() 可以工作

【讨论】:

  • 没有理由用新对象覆盖导出。最好简单地分配module.exports.runTest = runTest;
猜你喜欢
  • 2021-11-25
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 2015-11-12
  • 2023-01-31
相关资源
最近更新 更多