nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
104.76k stars 28.3k forks source link

fs.existsSync does not seem to work synchronously #52953

Closed cfish68 closed 1 month ago

cfish68 commented 1 month ago

Version

v18.19.1, v20.10.0

Platform

Linux Inspiron-5493 6.8.0-31-generic #31-Ubuntu SMP PREEMPT_DYNAMIC Sat Apr 20 00:40:06 UTC 2024 x86_64 x86_64 x86_64 GNU/Linux

Subsystem

No response

What steps will reproduce the bug?

const fs = require('fs');

if (!fs.existsSync('./new')){ fs.mkdir('./new', (err) => { if (err) throw err; console.log('Directory created'); }) }

if (fs.existsSync('./new')){ fs.rmdir('./new', (err) => { if (err) throw err; console.log('directory removed'); }) }else{ console.log('Directory does not exist'); }

How often does it reproduce? Is there a required condition?

When running from terminal the unexpected output is produced.

What is the expected behavior? Why is that the expected behavior?

The expected behavior is, given the directory 'new' does not exist, the program should produce and then immediately delete the directory 'new'. If it does exist then it should just delete it. This is the expected behavior because existsSync is expected to work synchronously .

What do you see instead?

It either creates the directory or deletes it, but not both.

Additional information

I checked this out on 2 versions both on a linux and a windows machine and I got the same result. When using a vsc debugger it did indeed give me the expected output.

marco-ippolito commented 1 month ago

You are mixing sync functions and async callback based function. Use mkdirSync and rmdirSync and it will work as expected