0
votes

I was coding an extension for vscode when I came across an error which I don't know how to fix. I am trying to make a script in which creates a file based on some inputs but when I am trying to get the path for the new file it returns an error! Here's the code:

let command3 = vscode.commands.registerCommand('command-bot.createFile', () => {
    var fileName = vscode.window.showInputBox({
        placeHolder: "Name your file"
    });
    var fileExt = vscode.window.showInputBox({
        placeHolder: "What is the extention example: .py or .html"
    });
    const folderPath = vscode.workspace.workspaceFolders[0].uri.toString().split(":")[1];
            //The code above caused the error! Error: Object is possibly 'undefined'
});
1

1 Answers

0
votes

workspaceFolders is only available when the user opens a workspace, but not if the user merely opens a folder.

So you might try to use something similar to below,

        let path: string;
        if (!workspace.workspaceFolders) {
            path = workspace.rootPath;
        } else {
            let root: WorkspaceFolder;
            if (workspace.workspaceFolders.length === 1) {
                root = workspace.workspaceFolders[0];
            } else {
                root = workspace.getWorkspaceFolder(resource);
            }

            path = root.uri.fsPath;
        }

https://github.com/vscode-restructuredtext/vscode-restructuredtext/blob/128.0.0/src/features/utils/configuration.ts#L154