'VSCode API check if path exists
In a VSCode extension, how can I check if a file path exists without opening or reading the file?
The closest thing I've found are vscode.workspace.fs.Readfile and vscode.workspace.openTextDocument (https://code.visualstudio.com/api/references/vscode-api#FileSystem), but again, I do not want to open or read the file. Is there a way to do this?
Solution 1:[1]
There is no API for that because there is a builtin function:
import * as fs from 'fs'; // In NodeJS: 'const fs = require('fs')'
if (fs.existsSync(path)) {
// File exists in path
}
Solution 2:[2]
Per @realappie's comment on another answer, you can use vscode.workspace.fs.
It doesn't have a method like exists, but you can use .stat() for that. An example from the repo:
try {
await vscode.workspace.fs.stat(jsUri);
vscode.window.showTextDocument(jsUri, { viewColumn: vscode.ViewColumn.Beside });
} catch {
vscode.window.showInformationMessage(`${jsUri.toString(true)} file does *not* exist`);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | nickf |
