Home > Enterprise >  Can a node module return a full path to one of its files?
Can a node module return a full path to one of its files?

Time:12-17

I'm pretty new with Node.js and currently implementing a node module that contains a zip. After installing (postinstall) the zip is extracted to a subfolder of the module. Moreover, the main.js script offers to callers a method that returns the full path to one of the extracted files.

The structure of the module look like this:

module_A
|- package.json
|- lib
|  └ postinstall.js
|- resources
|  └ ide.zip
|- extracted
|  └ ide.bat
└- main.js

So far the requirement seems "easy", however I'm running out of ideas on how to return the full path the the extracted file. Currently my main.js script look like this:

const path = require('path');

exports.getServerBatch = function() {
    return path.resolve('/extracted/ide.bat');
}

when using the module in another project ...

C:\projects\myproject\
              |- package.json (includes dependency to module_A)
              |- node_modules
              |  └ module_A
              |     |-main.js
              |     |-extracted
              |         └ ide.bat
              |     ...

... and debugging with VSCode, the returned path looks like the following:

C:\Users\<my_user>\AppData\Local\Programs\Microsoft VS Code\extracted\ide.bat

instead of:

C:\projects\myproject\node_modules\module_A\extracted\ide.bat

If I call the method from another place, the path changes. This makes me think that the full path depends always on where the application is being executed.

Is there a way of returning the full path I need without using the execution path?

CodePudding user response:

The path.resolve() function resolves the given path relatively to the process working directory which is in your case C:\Users\<my_user>\AppData\Local\Programs\Microsoft VS Code since vs code started the program in that location.

There is a global called __dirname which is the folder the file is located in.

You could try this in main.js



const path = require('path');

exports.getServerBatch = function() {
    // join concacinates paths. Handy for being crossplattform. I suggest to use it 
    // always for putting paths together.
    return join(__dirname, 'extracted', 'ide.bat');
}

Note:

Using __dirname could cause issues when using bundlers like webpack OR pkg. Some modules permit the usage of __dirname and always refer to using process.cwd() which is the programs working directory.

CodePudding user response:

After a little bit of more research I found a solution that seems to work fine:

module.exports.serverPath = path.join(__dirname, 'extracted/ide.bat');
  • Related