'VSCode Extension: How to open a file if no workspace folders are available?

I've been working on an extension that allows adding files with pre-defined content and modifying them using a custom web editor. The custom command "Add new XXX file" looks like the following:

    let disposable = vscode.commands.registerCommand('myextension.add-new-file', () => {
    if(vscode.workspace.workspaceFolders?.length){
        const rootPath = vscode.workspace.workspaceFolders[0].uri.fsPath ;
        let counter = 0;
        let filePath = '';
        do{
            counter++;
            filePath = path.join(rootPath, `NewFile${counter}.my-ext`);
        }while(fs.existsSync(filePath));
        fs.writeFileSync(filePath, JSON.stringify(newFileContent), 'utf8');
        const openPath = vscode.Uri.file(filePath); 
        vscode.commands.executeCommand('vscode.openWith', openPath, 'myextension.custom-designer');                 
    }
});

It works OK if a folder is opened in VS Code. However, if no folder is opened, the rootPath can't be resolved. What's the solution for such a scenario? Does the 'vscode.openWith' accept the file content instead of the path to open?



Solution 1:[1]

You can accomplish your goal using the untitled scheme:

vscode.commands.executeCommand(
  'vscode.openWith',
  vscode.Uri.parse("untitled:FooBar"),
  'myextension.custom-designer',
);

You can change your custom editor so that it detects when empty document gets passed to it and replaces the empty document with newFileContent.

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 Ark-kun