代码之家  ›  专栏  ›  技术社区  ›  WestCoastProjects

无法从自定义node.js模块导出函数

  •  0
  • WestCoastProjects  · 技术社区  · 3 年前

    node.js processTest.js 归档 node.js module.export s包括一个函数 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 模块实际存在且功能可见。

    enter image description here

    1 回复  |  直到 3 年前
        1
  •  2
  •   pxDav    3 年前

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

    或者干脆换个颜色 module.exports

    module.exports = {
        runTest
    }
    

    require("./processTest").runTest() 行得通