首页 > 解决方案 > VS Code API 返回带有 URI 的未知 URL 方案

问题描述

我很抱歉这个标题有点令人困惑。这是我遇到的问题的要点,我似乎无法弄清楚是什么原因造成的。我正在尝试编写一个简单的 VS Code 扩展来打开一个包含本地 JS 文件的 web 视图:

//CODE SNIPPET #1
const jsFilePath = vscode.Uri.file(
    path.join(context.extensionPath, 'src', 'assets', 'script.js')
);
const jsFileSrc = currentPanel.webview.asWebviewUri(jsFilePath);
//Pass the jsFileSrc URI as a parameter to getWebViewContent so that I can add the URI to the <script> tag that call the JS.
currentPanel.webview.html = getWebViewContent(jsFileSrc);

足够简单,它本身就可以完美运行。下一步是我需要检查特定文件夹的用户当前项目文件结构(并最终从该文件夹中拉出一个 .txt 文件并在 Javascript 中使用它)。

//CODE SNIPPET #2
//Check that the Annotations folder exists
const rootFolderPath = vscode.workspace.rootPath + "/annotations";
if(fs.existsSync(rootFolderPath)){
    vscode.window.showInformationMessage("Folder Was Found!");
    return true;
} else {
    vscode.window.showErrorMessage("No folder titled 'annotations' found in root path " + vscode.workspace.rootPath + ". Please close the extension and try again.");
    return false;
}

这看起来也很简单,它只是检查工作区中是否存在“注释”文件夹。如果我将代码片段 #2 放在代码片段 #1 的下方,这一切都可以正常工作。然而,第二次我将代码片段 #2 放在代码片段 #1 上方的任何位置,我收到此错误:

加载资源失败:net::ERR_UNKNOWN_URL_SCHEME

这是我每次运行 Web 视图时附加到 HTML 文档的 URL。同样,当我将代码片段 1 放在代码片段 2 之前时,它工作得非常好,但是当我颠倒顺序时,我得到了 Unknown URL Scheme 错误——即使每次都返回相同的 URL。

vscode-resource://file///Users/user/Desktop/Project/NLP/Webviewer/rule-editor/src/assets/script.js

我已经阅读了大量的文档,但我似乎无法弄清楚为什么会这样。我需要能够检查此文件夹并检索此文件夹内的 .txt 文件,以便将其添加到 webview。任何帮助将不胜感激,谢谢!

标签: visual-studio-codeurivscode-extensions

解决方案


我想我可能已经发现了这个问题。看来 fs.existsSync 已被弃用。对于 VS Code api,最好使用 vscode.workspace.fs ( https://code.visualstudio.com/updates/v1_37#_vscodeworkspacefs )。

这是代码片段 #2 的修订版,适用于遇到相同问题的任何人,这可能会帮助您走上正确的轨道。

var rootPath: string;
if(vscode.workspace.rootPath){
    rootPath = vscode.workspace.rootPath.toString();
    const rootFolderPath = vscode.Uri.file(
        path.join(rootPath, 'annotations')
    );
    vscode.workspace.fs.readDirectory(rootFolderPath).then(results => {
        results.forEach(result => {
            //This will print out a list of all the files inside of the dir.
            console.log(result);
        });
    });
}

推荐阅读