5

I have a package.json like this:

...
  "scripts": {
    "dev": "webpack --config webpack.dev.config.js --mode development --progress --colors",
    "postdev": "if (Test-Path \"./postdev.sh\" ) { echo \"file exists\"; ./postdev.sh }"
  },
...

How can I check if file "postdev.sh" exists and then launch it in NPM-scripts section? I run that command in the terminal and it goes correctly, but if I try to launch that npm-script it says "Unexpected appearance: "./postdev.sh"."

1

4 Answers 4

6

You can use path-exists-cli package, a cross-platform tool, to check if a file/directory exists and use && or || after to run the next command if exists or not, respectively:

{
  "scripts": {
    // other scripts...
    "postdev": "path-exists ./postdev.sh && echo 'Exists' || echo 'Does not exists'"
  }
}
3

on macos or linux try this one for postdev:

"postdev": "test -f ./postdev.sh && echo 'file exisits' && ./postdev.sh",
2
2

Finnally found a solution (maybe it works only on Windows, but it is enough for me):

"postdev": "if exist postdev.sh ( postdev.sh )",
0

I want to say that smth && script or smth && script || : are not good solutions. First one still fails when smth fails and you won't be able to ignore not existing file case. Second one is bad, because you are ignoring fails from smth and script together.

Then I prefer to use shell script here:

"postinstall": "sh -c 'if [ -f ./dist/postinstall.js ]; then node ./dist/postinstall.js; fi'"

It runs postinstall when we have dist folder and doesn't ignore postinstall script fails.

Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.