0

I've tried a few different npm packages that open files and I have the same issue with all of them.

https://www.npmjs.com/package/opn
https://www.npmjs.com/package/open

the problem: I am not able to open multiple html files on my hard drive at once. but when I try to open just one of them it works fine. any idea what's causing this issue?

This DOESN'T work (the web pages don't open in my browser):

var fs = require('fs');
var opn = require('opn');

fs.writeFile('open.html', 'hello');
fs.writeFile('open1.html', 'hello1');
fs.writeFile('open2.html', 'hello2');
fs.writeFile('open3.html', 'hello3');
fs.writeFile('open4.html', 'hello4');
fs.writeFile('open5.html', 'hello5');

console.log('files created');

opn('open.html');
opn('open1.html');
opn('open2.html');
opn('open3.html');
opn('open4.html');
opn('open5.html');

BUT the code below WORKS (the one web page opens fine in my browser):

var fs = require('fs');
var opn = require('opn');

fs.writeFile('open.html', 'hello');

console.log('file created');

opn('open.html');
2
  • Perhaps it is by design that this is happening. Have you tried requiring opn separately for each file you want to open? Commented May 5, 2016 at 16:55
  • @BlazeSahlzen I tried adding a 'setTimeout(function() {}, 500);' around the multiple opns and it worked properly. perhaps fs.write can't create the file fast enough and there is no file for opn to open? Is there a way to skip the writing of the file and just have the html in a variable and open a website with that variable being the code? something like: var abc = 'my html code'; open('test.hml', abc) Commented May 5, 2016 at 17:12

1 Answer 1

1

If you're aware of the side effects, you can use fs.writeFileSync instead of fs.writeFile: https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options

fs.writeFileis asynchronous and will return immediately (even if the file is not created yet). You can use it with a callback if you want to wait for the operation to finish.

fs.writeFileSync blocks the main thread until the file is written, and returns only then. If you don't want to change your code too much, you can probably just use that.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for clarifying. I was able to use fs.writeFile and use the callback to open the page. this works perfectly.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.