1
  • Folder1
    • file1.js
  • Folder2
    • file2.js

I want to check if file2.js exists, from file1.js using fs (they're in different folders)

I haven't been able to find a way I can do this, without listing the whole directory of file2.js.

Does anyone know the best way to achieve this?

2 Answers 2

1

Use fs.existsSync:

In you file1.js

if (fs.existsSync(__dirname + '/../Folder2/file2.js')) {
    console.log('Found file');
}
Sign up to request clarification or add additional context in comments.

2 Comments

__dirname + '../Folder2/file2.js' gives me directory/folder1../folder2/file2.js. I need it to give me directory/folder2/file2.js instead
Updated my answer missed a slash before ../. You can't directly get to that directory but you can check relative to your own directory that is relative to file1.js
0

I do not agree file path use string + string. There is a way that use path.join is more safe and more right than string and more information can see here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.