简体   繁体   中英

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

I have certain files within the VSCode extension src folder that I would like to copy into the root of the workspace on running a certain command. Once this is working I would also like to extend this to copy other static files with specific content into other sub-folders within the workspace. I found a way to create new files here . However, I am unable to find a way to copy entire files bundled within the extension into the workspace. Looking at the MSFT documentation here , I cannot find anything that would work for my use case. Any pointers are appreciated.

I created a function copyFile that can copy file from within a VSCode extension to the workspace at the provided destination.

You can use WorkspaceEdit and FileSystem VS Code API to achieve this task as shown below.

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);
  }
}

Sample function call:

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) {});
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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