JavaScript NodeJs Open Library

Viewed 165

I am trying to open multiple images simultaneously in the default Windows Photo Viewer that I have stored in my folder using the npm open library:

let files = ['Dog.gif', 'Cat.jpeg'];
for(let i=0; i<files.length; i++){
  open(`${files[i]}`, {wait:true});
}

But it's only opening the first file? I am not sure how to fix this?

2 Answers

in my case, it happened because the file name or file type did not exist or did not match the source file

{wait: true} is supposed to cause open() to wait until you exit the application that opens the file before resuming execution. So if you expect them all to open at the same time, remove the {wait: true} option.

If you, in fact, do want it to wait until the application exits before opening the second file and hare having it only open one file, read on for at least some minimal debugging help.

Assuming you are using a recent version of open, it is a promise-based API. It seems to make it hard to get at errors. However, you can at least confirm that you're getting an error like this:

const open = require('open');

let files = ['dog.txt', 'cat.txt'];
(async () => {
  for(let i=0; i<files.length; i++){
    const cp = await open(`${files[i]}`, {wait: true});
    console.log(`${files[i]} exit code: ${cp.exitCode}`);
  }
})();

That will print an error code of 0 for all files where open() succeeded and a non-zero value for all files where open() failed.

Related