0

I'm starting with NodeJS, and I've looked for the answer in here but haven't found anything useful yet. I have a function that receives a path and needs to check first whether that path is valid, whether a file or directory exists there in the end or not. My program needs to be sync, I need to check first whether the path received is valid, then if the file exists. Thank you

lgz
  • 3
  • 2
  • Does this answer your question? [Node.js check if file exists](https://stackoverflow.com/questions/17699599/node-js-check-if-file-exists) – derpirscher Sep 03 '22 at 21:14
  • 2
    What do you mean by *valid*? Can you show an example of invalid path? – Konrad Sep 03 '22 at 21:14
  • You don't, because it is a race. Right after you check that the path exists, I can giggle and sneak in and rename one of the directories in the path. – doug65536 Aug 21 '23 at 22:06
  • The operating system does the required synchronization when it is traversing the path. You just open it. How do you create a directory if it maybe exists? You just create it, and expect an EEXISTS. – doug65536 Aug 21 '23 at 22:16

1 Answers1

1

If by valid you mean following the rules of path syntax, then what you need is to check using a regular expression. An example is:

console.log(/^(\/?[a-z0-9]+)+$/.test('/dir1/dir2')); // true
console.log(/^(\/?[a-z0-9]+)+$/.test('/dir1/dir2//')); // false

/^(\/?[a-z0-9]+)+$/ is the regular expression, this regex matches strings like /a/b/c. You can find more about regex here and here, here instead you can test regex. Also, here you can find examples of regex for windows paths.

agimarco
  • 74
  • 5