简体   繁体   中英

Reading & writing data to a .txt file using vscode extension api

So I am new to this vscode extension api. I have this functionality where I need to take input from the user when they click on certain line and then get the 1). input value, line number and file name 1). input value, line number and file name and 2). store it to a text file 2). store it to a text file .

I am done with the first part, I am getting the data everything. Now I have to just write it to the file and if there is data already, new data should be appended not overwritten.

I have tried using fs.writeFileSync(filePath, data) and readFileSync but nothing, I do not know if I am doing it correctly. If someone can point me in the right direction I am just blank at this stage?

Any help would be appreciated, Thanks in advance.

The FS node module works fine in an extension. I use it all the time for file work in my extension . Here's a helper function to export something to a file with error handling:

/**
 * 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 + "'.");
                }
            });
        }
    });
}

And here an example where I read a file without user intervention :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM