当我遇到一个不知道如何解决的错误时,我正在为vscode编写扩展。我试图创建一个脚本,在其中基于一些输入来创建文件,但是当我尝试获取新文件的路径时,它将返回错误!这是代码:
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'
});
答案 0 :(得分:0)
workspaceFolders
仅在用户打开工作区时可用,而在用户仅打开文件夹时不可用。
所以您可以尝试使用类似于下面的内容,
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;
}