我正在尝试创建一个文件作为扩展中命令之一的一部分,但似乎无法正确完成。
let wsedit = new vscode.WorkspaceEdit();
const file_path = vscode.Uri.file(value + '/' + value + '.md');
vscode.window.showInformationMessage(file_path.toString());
wsedit.createFile(file_path, {ignoreIfExists: true});
vscode.workspace.applyEdit(wsedit);
vscode.window.showInformationMessage('Created a new file: ' value + '/' + value + '.md);
value
是用户输入的字符串。代码执行了,但据我所知,没有创建文件。如何正确创建文件?
vscode.Uri
不支持相对路径(here是相应的问题)。话虽如此,您必须使用绝对路径。以下代码片段应该可以工作(在 Windows 上使用 vscode v1.30.0 进行测试)
const wsedit = new vscode.WorkspaceEdit();
const wsPath = vscode.workspace.workspaceFolders[0].uri.fsPath; // gets the path of the first workspace folder
const filePath = vscode.Uri.file(wsPath + '/hello/world.md');
vscode.window.showInformationMessage(filePath.toString());
wsedit.createFile(filePath, { ignoreIfExists: true });
vscode.workspace.applyEdit(wsedit);
vscode.window.showInformationMessage('Created a new file: hello/world.md');
您可以使用 (writeFile)[https://code.visualstudio.com/api/references/vscode-api#workspace.fs.writeFile] 实现相同的效果,并且代码要少得多。
vscode.workspace.fs.writeFile(filePath, Buffer.from(''))
它根据需要创建文件和目录。 注意:如果文件存在,它将替换该文件的内容。