VSCode 扩展写入和打开文件

VSCode Extension write and open file

其实我的需求很简单,就是写一个文件,然后在vscode中打开。但我无法让它工作:

var content = rec[rt.fields[field]];
var filePath = path.join(vscode.workspace.rootPath, selected.label + '.' + field);
fs.writeFileSync(filePath, content, 'utf8');

var openPath = vscode.Uri.parse(filePath);
vscode.workspace.openTextDocument(openPath).then(doc => {
  vscode.window.showTextDocument(doc);
});

我收到以下错误消息,但不知道那是什么意思:

cannot open c:%5CUsers%5Cmak%5C.sneditor%5Csoftpointdev1.service-now.com%5CRMCostPlanHelper.js. Detail: No model with uri 'c:%5CUsers%5Cmak%5C.sneditor%5Csoftpointdev1.service-now.com%5CRMCostPlanHelper.js' nor a resolver for the scheme 'c'.

一发布这个问题我就找到了答案^^

你必须使用 vscode.Uri.file 而不是 vscode.Uri.parse

const content = 'exampleContent';
const filePath = path.join(vscode.workspace.rootPath, 'fileName.extension');
fs.writeFileSync(filePath, content, 'utf8');

const openPath = vscode.Uri.file(filePath);
vscode.workspace.openTextDocument(openPath).then(doc => {
    vscode.window.showTextDocument(doc);
});

我也遇到了类似的问题。您还可以通过执行以下操作来解决您的问题:

var content = rec[rt.fields[field]];
var filePath = path.join(vscode.workspace.rootPath, selected.label + '.' + field);
fs.writeFileSync(filePath, content, 'utf8');

var openPath = vscode.Uri.parse("file:///" + filePath); //A request file path
vscode.workspace.openTextDocument(openPath).then(doc => {
  vscode.window.showTextDocument(doc);
});