简体   繁体   中英

Wait input end before executing next code?

I'm using this piece of code to to try triggering an input and then read the file path, so I can load it as text in a div :

var fileinput = $("input[id=fileDialog]").trigger('click');

var fs = require('fs');

fs.readFile(path, 'utf8', function(err, txt) {
  if (err) {
    return;
  }

  document.getElementById('content').innerText=txt
});

Problem is, it seems that the jQuery part is async, so the following code doesn't wait for it to finish, and that generate problems.

How can I make the code wait for the input to close before executing?

I think the problem is that your fs.readFile Asynchronously reads the entire contents of a file while execution moves to next statement.

you can use Synchronous version of fs.readFile() . ie fs.readFileSync that returns the contents of the path.

Full details are here https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM