Home > Blockchain >  VSC Extension – Can't load text file using relative path in extension.ts
VSC Extension – Can't load text file using relative path in extension.ts

Time:01-01

I am trying to write an extension that, when invoked using encloseTag command, shows a list of preset tags loaded from a text file and encapsulates selected text in that tag. I got it to work, but only if I specify a static path – using relative path doesn't work, I get these errors instead:

Error reading tags file: ENOENT: no such file or directory, open 'tags.txt'
Activating extension 'undefined_publisher.enclosingtags' failed: ENOENT: no such file or directory, open 'c:\Users\username\ProjectPublisher\out\FILENAME'.

When I tried printing the working directory, it was nowhere near the project directory (it was in AppData instead of the project location in the User folder). I am not sure how I can influence this or if this is issue with VSC or my code. Note: I am executing it using debug from VSC (by pressing F5).

How can I get this code to use the tags file from the same dir as the extension.ts file?

package.json:

(…)
"contributes": {
    "commands": [
      {
        "command": "encloseTag",
        "title": "Enclose in Tag"
      }
    ]
},
(…)

extension.ts:

import * as vscode from 'vscode';
import * as fs from 'fs';

export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand('encloseTag', () => {

        let editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showErrorMessage('No active text editor');
            return;
        }
        let selection = editor.selection;
        let text = editor.document.getText(selection);
        if (!text) {
            return;
        }

        let tags: string[] = [];
        try {
            let data = fs.readFileSync('C:\\Users\\username\\ProjectPublisher\\tags.txt', 'utf8');
            // Split the data into lines and remove leading and trailing whitespace and newline characters from each line
            tags = data.split('\n').map(line => line.trim().replace(/\r?\n|\r/g, ''));
        } catch (error: any) {
            vscode.window.showErrorMessage('Error reading tags file: '   error.message);
            return;
        }

        // Prompt the user to select a tag
        vscode.window.showQuickPick(tags).then((tag) => {
            if (!tag) {
                return;
            }

            // Enclose the selected text in the chosen tag
            let newText = `<${tag}>${text}</${tag}>`;
            editor.edit(edit => {
                edit.replace(selection, newText);
            });
        });
    });

    context.subscriptions.push(disposable);

    const fs = require('fs');
    fs.readFileSync(`${__dirname}\\FILENAME`);
}

export function deactivate() {}

tags.txt:

tag1
tag2
tag3

input: This is some text to annotate.

output: This is some text to annotate.

CodePudding user response:

construct an absolute path using the file path in the context (argument of activate function)

export function activate(context: vscode.ExtensionContext)

The absolute file path of the directory containing the extension

ExtensionContext::extensionPath
  • Related