0

I am trying to make a vscode extension and one of the things I am trying to do is create/edit a file when using a specified command. I have the command working.

when I try run the following code using "node test.js", the fs.writeFileSync() method creates the file as expected.

let fs = require('fs');

try {
    fs.writeFileSync("test.txt", "Test success!");
} catch (error) {
    console.log(error);
}

However when I run my custom command from my "extension.js" file (code below), I see the pop up message "Testing!", but no file is created by the fs.writeFileSync() method. I don't get any errors either. My only guess is that there is an unknown restriction in place that keeps the code from creating files. Does anybody have any ideas how I can get fs.writeFileSync() to work?

const vscode = require('vscode');
let fs = require('fs');
        
/**
* @param {vscode.ExtensionContext} context
*/
        
        function activate(context) {
    
            console.log('Congratulations, your extension is now active!');
            
            let disposable = vscode.commands.registerCommand('extension.test', () => {
            
            vscode.window.showInformationMessage('Testing!');
            
                try {
                    fs.writeFileSync("test.txt", "Test success!");
                } catch (error) {
                    console.log(error);
                }
        });
        
        context.subscriptions.push(disposable);
    }
        
    function deactivate() {}
        
    module.exports = {
        activate,
        deactivate
    }

Thanks in advance, Vectorjon

vectorjon
  • 31
  • 6
  • 1
    "*no file is created*" - how do you know? What path are you even expecting the file to be written to? – Bergi Sep 30 '21 at 19:00
  • @Bergi The path is relative and the file should be created in the same directory as the *.js files. test.js works while extension.js doesn't. – vectorjon Sep 30 '21 at 19:10
  • 1
    You mean the same directory as the `extension.js` file? That sounds like a bad idea. Anyway, that's what [`__dirname`](https://nodejs.org/docs/latest/api/modules.html#modules_dirname) is for. You can try to include [`process.cwd()`](https://stackoverflow.com/questions/9874382/whats-the-difference-between-process-cwd-vs-dirname) in your `showInformationMessage` to find the file that it has actually written so far. – Bergi Sep 30 '21 at 19:14
  • @Bergi Thanks, I see what has happened. The file is being written to the location returned by `process.cwd()` (my "Microsoft VS Code" folder). I'll use `_dirname` to get it to the right location. Thanks again! – vectorjon Sep 30 '21 at 19:31

0 Answers0