繁体   English   中英

如何将 VSCode 扩展中的文件复制到工作区?

[英]How do I copy files from within a VSCode extension to the workspace?

我在 VSCode 扩展src文件夹中有某些文件,我想在运行某个命令时将它们复制到工作区的根目录中。 一旦这工作正常,我还想扩展它以将具有特定内容的其他 static 文件复制到工作区中的其他子文件夹中。 我在这里找到了一种创建新文件的方法。 但是,我无法找到将扩展中捆绑的整个文件复制到工作区的方法。 查看此处的 MSFT 文档,我找不到适合我的用例的任何内容。 任何指针表示赞赏。

我创建了一个 function copyFile ,它可以将文件从 VSCode 扩展名复制到提供的目的地的工作区。

您可以使用WorkspaceEditFileSystem VS Code API 来完成此任务,如下所示。

async function copyFile(
  vscode,
  context,
  outputChannel,
  sourcePath,
  destPath,
  callBack
) {
  try {
    const wsedit = new vscode.WorkspaceEdit();
    const wsPath = vscode.workspace.workspaceFolders[0].uri.fsPath;
    const data = await vscode.workspace.fs.readFile(
      vscode.Uri.file(context.asAbsolutePath(sourcePath))
    );
    const filePath = vscode.Uri.file(wsPath + destPath);
    wsedit.createFile(filePath, { ignoreIfExists: true });
    await vscode.workspace.fs.writeFile(filePath, data);
    let isDone = await vscode.workspace.applyEdit(wsedit);
    if(isDone) {
      outputChannel.appendLine(`File created successfully: ${destPath}`);
      callBack(null, true);
    }
  } catch (err) {
    outputChannel.appendLine(`ERROR: ${err}`);
    callBack(err, false);
  }
}

样品 function 调用:

function activate(context) {
  ...
  let testChannel = vscode.window.createOutputChannel("TestChannel");
  // copy tasks.json file from vs code extension to the destination workspace
  copyFile(vscode, context, testChannel, 
           'assets/tasks.json', '/.vscode/tasks.json', function(err, res) {});
  ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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