shinnn / run-in-dir

Run a function with changing the current working directory to a given path

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

run-in-dir

npm version Build Status codecov

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

Installation

Use npm.

npm install run-in-dir

API

const runInDir = require('run-in-dir');

runInDir(dir, fn)

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')
  });
});

License

ISC License © 2019 Watanabe Shinnosuke

About

Run a function with changing the current working directory to a given path

License:ISC License


Languages

Language:JavaScript 100.0%