0

I know it's a bad practice, but it would be helpful to know how to deal with certain cases.

In my case I'm trying to create some files, then read them. I'm wondering how can I wait for the creation to complete, before I try to read their containing directory, without using setTimeout and conditions?

5
  • What OS are you using? Is it Microsoft's Windows? Commented Nov 25, 2018 at 13:31
  • yes is it relevant? Commented Nov 25, 2018 at 13:33
  • Are you saying that you are creating files, and then look to see if they exist, and that there is a race condition, such that they may not yet exist? And is it because you are doing it in two synchronise threads/co-routines? Please add detail to question. Commented Nov 25, 2018 at 13:37
  • in my case I'm reading base64 data ,decoding it ,creating files with those data and trying to read those file after their creation , since the creation takes some time the fs.readdirsync is reading an empty folder, any trick would be very much helpful i've already tried the promises , co , async and many more Commented Nov 25, 2018 at 13:42
  • Use fs.writeFileSync() and fs.readFileSync() Commented Nov 27, 2018 at 13:45

2 Answers 2

2

A lot of NodeJS function have synchronous counterparts, you should look for those.

Have a look at the documentation for File System at https://nodejs.org/api/fs.html. Do a page search for 'sync' and you can see that it offers many synchronous functions.

It's not just File System that offer this. The Child_process does the same, see https://nodejs.org/api/child_process.html#child_process_child_process_execsync_command_options for example.

If you can't find a native synchronous version of a function you need, the npm registry is a good place to look, a lot of times you can find a synchronous package there.

Good luck!

p.s. It's not always bad practice to write synchronous code in NodeJS, many CLI tools are synchronous for example.

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

Comments

0

You can use async await or promise to accomplish it

Example:-

async function f() {
  return 1;
}

You can pass your method inside it. it will wait till your response comes

2 Comments

usualy in promisses you have to specify when to resolve and when to reject with a condition if my condition goes something like if (fs.readdirsync(directory) === DataFiles.length){resolve} it would never goes into it because the directory is still empty
I think the OP will need a better example. They have tried promises. Can you show them how. (I don't use node.js, so won't get it right.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.