2

I'm trying to create a oneliner in node using exec. The idea is to create a folder called admin and unzip untar a file into it, so:

mkdir admin
tar xvfz release.tar.gz -C admin/

The problem is, sometimes admin exists (its ok, I want to overwrite it contents), and that using exec will trigger an error:

exec('mkdir admin && tar xvfz release.tar.gz -C admin/', (err, stdout, stderr) => {
  if(err) { //mkdir fails when the folder exist }
});

Is there a way to elegantly continue if mkdir fails? Ideally, I want to clean the contents of admin like rm -rf admin/ so the new untar start fresh, but then again, that command will fail.

PS: I know I can check with FS for the folder before lunching exec, but Im interested on an all in one exec solution. (if possible)

EDIT: The question How to mkdir only if a dir does not already exist? is similar but it is about the specific use of mkdir alone, this instead is about concatenation and error propagation.

DomingoSL
  • 14,920
  • 24
  • 99
  • 173

1 Answers1

3

You don't need to have mkdir fail on an existing target, you can use the --parents flag:

-p, --parents
no error if existing, make parent directories as needed

turning your oneliner into:

exec('mkdir -p admin && tar xvfz release.tar.gz -C admin/', (err, stdout, stderr) => {
  // continue
});

Alternatively, you could also use ; instead of && to chain the calls which will always continue, no matter the exit code:

exec('mkdir admin; tar xvfz release.tar.gz -C admin/', (err, stdout, stderr) => {
  // continue
});
m90
  • 11,434
  • 13
  • 62
  • 112