简体   繁体   中英

How to load resource from a relative path in a nodejs module?

In one of my NodeJS modules I need to access a file that is part of the module in an own folder (for unit tests). It tried __dirname in the calling file with a relative path to that resource file. This works when running from within vscode, but not whe executing npm test in a terminal. In that case the constructed path is one level off. How can that be?

I have to add that I'm using typescript for coding and Mocha for unit tests.

Simply logging __filename helps a bit here. It shows that under vscode the executing file is the transpiled JS file, while under Mocha it's the typescript source file. I run:

mocha --compilers ts:ts-node/register,tsx:ts-node/register

for my tests. Any idea how to overcome this and ensure the correct path is used (other than testing if __filename ends with .ts )?

Ok, turns out to be simple. Instead of running mocha with ts code let it use the transpiled code. Only requires a transpilation run before testing:

  "scripts": {
    "prepublish": "tsc",
    "install": "tsc",
    "test": "tsc && mocha out/test"
  },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM