【问题标题】:Reading & writing data to a .txt file using vscode extension api使用 vscode 扩展 api 读取和写入数据到 .txt 文件
【发布时间】:2021-02-09 00:23:14
【问题描述】:

所以我是这个 vscode 扩展 api 的新手。我有这个功能,当用户单击某行时,我需要从用户那里获取输入,然后获取 1). input value, line number and file name2). store it to a text file

我已经完成了第一部分,我正在获取所有数据。现在我只需将其写入文件,如果已经有数据,则应追加新数据而不是覆盖。

我尝试过使用fs.writeFileSync(filePath, data) and readFileSync 但没有,我不知道我是否正确使用。如果有人能指出我正确的方向,我在这个阶段只是空白吗?

任何帮助将不胜感激,在此先感谢。

【问题讨论】:

  • 包含显示您尝试过的代码并解释“我尝试过......但没有”的意思。

标签: file visual-studio-code vscode-settings fs vscode-extensions


【解决方案1】:

FS 节点模块在扩展中工作正常。我一直用它来处理my extension 中的文件。这是一个辅助函数,用于将某些内容导出到具有错误处理的文件:

/**
 * Asks the user for a file to store the given data in. Checks if the file already exists and ask for permission to
 * overwrite it, if so. Also copies a number extra files to the target folder.
 *
 * @param fileName A default file name the user can change, if wanted.
 * @param filter The file type filter as used in showSaveDialog.
 * @param data The data to write.
 * @param extraFiles Files to copy to the target folder (e.g. css).
 */
public static exportDataWithConfirmation(fileName: string, filters: { [name: string]: string[] }, data: string,
    extraFiles: string[]): void {
    void window.showSaveDialog({
        defaultUri: Uri.file(fileName),
        filters,
    }).then((uri: Uri | undefined) => {
        if (uri) {
            const value = uri.fsPath;
            fs.writeFile(value, data, (error) => {
                if (error) {
                    void window.showErrorMessage("Could not write to file: " + value + ": " + error.message);
                } else {
                    this.copyFilesIfNewer(extraFiles, path.dirname(value));
                    void window.showInformationMessage("Diagram successfully written to file '" + value + "'.");
                }
            });
        }
    });
}

这里有一个例子,我read a file without user intervention:

    this.configurationDone.wait(1000).then(() => {
        ...
        try {
            const testInput = fs.readFileSync(args.input, { encoding: "utf8" });
            ...

        } catch (e) {
            ...
        }
        ...
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-04
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    相关资源
    最近更新 更多