Search code examples
node.jsasync-awaitrequire

Exported functions are not showing after import in NodeJS


I'm trying to import some async-await functions from a file. However, it seems that none of the exports become visible after importing. I'm only seeing this issue with asyc-await. As far as I can see, I did the same thing with normal function and it seems to work okay.

The file I'm trying to import is helper.ts with code like:

 // some dependencies like below:
 import mydriver from "driver";

 const driver = mydriver.driver(
    // connection settings
 );

 module.exports = {
   myFunction: async (arg) => {
     const session = driver.session();
     var result = await session.writeTransaction(
       // a query
     );
     session.close();
     return result;
   }
}

Then in another file I import this like:

import helper = require("./helper");

// Below line throws error
var result = helper.myFunction(arg);

The error is

Property 'myFunction' does not exist on type 'typeof "/mydirectory/helper"'


Solution

  • This line:

    import helper = require("./helper");
    

    should be:

    const helper = require('./helper');
    

    It looks like you will possibly have multiple functions to export, in which case this alternate syntax for assigning to module.exports is available as discussed in https://stackoverflow.com/a/38174623/8954866

       const privateFn = () => { }
    
       module.exports = {
          async myFunction (arg) {
            // method body
            return result;
          },
    
          async Foo () {
            // method body
            privateFn()
            this.myFunction("bar")
          }
        }