Run a function with changing the current working directory to a given path temporarily
const {resolve} = require('path');
const runInDir = require('run-in-dir');
process.cwd(); //=> /Users/shinnn/example
resolve('A'); //=> /Users/shinnn/example/A
runInDir('fixtures', () => {
process.cwd(); //=> /Users/shinnn/example/fixtures
resolve('A'); //=> /Users/shinnn/example/fixtures/A
});
process.cwd(); //=> /Users/shinnn/example
resolve('A'); //=> /Users/shinnn/example/A
npm install run-in-dir
const runInDir = require('run-in-dir');
dir: string
(a directory path where fn will be invoked)
fn: Function
(a non-async one)
Return: any
(return value of fn)
It changes the current working directory to dir, call fn and immediately change back to the original working directory.
Note that the change of the current working directory is effective only in the current event loop.
process.cwd(); //=> /Users/shinnn/example
runInDir('fixtures', () => {
process.cwd(); //=> /Users/shinnn/example/fixtures
process.nextTick(() => {
process.cwd(); //=> /Users/shinnn/example (not '/Users/shinnn/example/fixtures')
});
});
ISC License © 2019 Watanabe Shinnosuke