1

I am testing out a simple node.js custom module represetned by the processTest.js file in the node.js root directory. Here is its contents: notice that the module.exports includes the one function 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;

In the main node.js script we try to invoke it as follows:

const processTest = require("./processTest")

...

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

However we get the error

Uncaught TypeError: processTest.runTest is not a function

note that the processTest module is actually present and the function is visible.

enter image description here What is wrong here and how should it be corrected?

2
  • Try processTest() instead? Commented Sep 15, 2021 at 0:17
  • processTest() did not work - I needed to change the module exports as shown in the [soon to be] accepted answer Commented Sep 15, 2021 at 0:21

1 Answer 1

2

You are referring to the function in the processTest file. (module.exports = runTest). Use require("./processTest")()

Or just change the module.exports to

module.exports = {
    runTest
}

and require("./processTest").runTest() will work

Sign up to request clarification or add additional context in comments.

1 Comment

No reason to overwrite the export with a new object. It's much better to simply assign module.exports.runTest = runTest;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.