1

I have a NodeJS module that does a lot of work on the filesystem in a particular directory. I would like all filesystem operations inside the module to be done relative to that directory - (let's call it /home/me/data).

I realise I could change the current working directory with process.chdir("/home/me/data"); but that would mess up the working directory of any other modules that are using my module.

Is there a way that a child module can have a different working directory than it's parent?
I don't want to have to pass a variable through to every sub-module to be appended to the filepath of fs.readFile(filepath); calls.

Are there any elegant ways of achieving this?

P.s. child process spawning / forking is not appropriate here.

Mike Monteith
  • 521
  • 1
  • 6
  • 18

2 Answers2

0

No. The cwd is one-per-process in unix. In general, code that explicitly references cwd in usually misguided. It only makes sense for certain utilities like git, and even then the OS handles relative to absolute conversion for you. Have you considered expanding your paths with path.resolve so they are absolute before passing them to the module in question?

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • At the moment I am passing a resolved path to the module. The issue is that the module has to pass that path to each of it's sub-modules and their sub-modules etc... Just seems a little bit messy – Mike Monteith May 14 '15 at 15:26
  • Hey @Peter, can you expand your answer on why referencing `cwd` from a submodule is usually misguided? `path.resolve` will eventually use `cwd` for example. – Andrew Lavers May 14 '15 at 15:35
  • I'll make you a deal. you add concrete details to your question to replace the vague/abstract stuff and I'll expand my answer. what Durr's your program do and why? how is cwd relevant at all? – Peter Lyons May 14 '15 at 16:18
0

The 'relative-fs' module on NPM is one solution https://www.npmjs.com/package/relative-fs - It wraps the fs library to make it's methods relative to a given directory.

disclaimer: I haven't actually used it yet.

Mike Monteith
  • 521
  • 1
  • 6
  • 18