Sven
Sven

Reputation: 53

DRY way to change working directory for npm scripts

I'm just trying out NPM as my build system for a small project and I'd like to ask if there is a clean and easy to maintain way to change the working directory for the build scripts. My first thought was something like

"scripts": {
    "cd:workdir": "cd src/path/to/my/work/dir/",
    "task:1": "npm run cd:workdir && command1",
    "task:2": "npm run cd:workdir && command2",
    [...]
  }

But it seams command* is executed in a different process then npm run cd:workdir, so this doesn't work.

The only working way I found so far is:

"scripts": {
    "task:1": "cd src/path/to/my/work/dir/ && command1",
    "task:2": "cd src/path/to/my/work/dir/ && command2",
    [...]
  }

But there must be a better way to do this to keep it DRY and better maintainable. Thanks!

Upvotes: 0

Views: 453

Answers (1)

Fazle
Fazle

Reputation: 11

I think you can use child_process.exec to execute some commands from a javascript file:

// task.js
const { exec } = require('child_process');

exec('command', {
  cwd: 'src/path/to/my/work/dir/'
}, (error, stdout, stderr) => {
  // handle error, stderr...

  console.log(stdout)
});

and execute that javascript file using node in npm script: "task:1": "node task.js"

Upvotes: 1

Related Questions