1

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

'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模块实际上存在并且该功能是可见的。

在此处输入图像描述 这里有什么问题,应该如何纠正?

4

1 回答 1

2

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

或者只是更改module.exports

module.exports = {
    runTest
}

并且require("./processTest").runTest()会工作

于 2021-09-15T00:17:50.553 回答