Validate path nodejs

Asked

Viewed 121 times

1

Hello, I’m developing a file manipulation system, and I just want it to be possible to manipulate folder with an absolute path for example /opt/file. In other words, I can only create/edit/delete folders in this path. I want to validate that the initial path is always /opt/file.

What’s the best way to do it? Thank you

1 answer

1


Whereas the path is one string you can use the function indexOf to identify whether the index is 0, i.e., whether the string in question starts with the text that was provided. It would look something like this:

...
if (path.indexOf('/opt/file') === 0) {
  // Faz o que deve fazer com o arquivo
...

indexOf

The method indexOf() returns the index of the first occurrence of the value specified in searchValue within the object String to which he was called, beginning the search from fromIndex. Returns -1 if value is not found.

Syntax

str.indexOf(searchValue[, fromIndex])

searchValue

A string representing the value to be searched for.

fromIndex

The position of the original string from which the search must begin. It can be any integer. The default value is 0. If fromIndex < 0 the whole string is traversed (equivalent to passing 0). If fromIndex >= str.length, the method will return -1.

  • 1

    Thanks, I managed to solve the problem just added another bar to the end if (path.indexOf('/opt/dir/'), to validate dir only. If no paths like dir1, dirx would also be valid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.