1 min read

Accidentally deleted your coding projects? Recover using VSCode History.

What should I do next?

Don't panic. This is a situation that I have been in for twice. If you are using Visual Studio Code as your editor, all the files that you have edited before are saved into your local history for the "Timeline" feature. First, close all your VSCode windows if they are opening any project folder. (This is to prevent VSCode from thinking that the project no longer exists and deletes the local history).

Then, let's use the magic of JavaScript. Create a recovery.js file (you can use VSCode as long as it is not in a directory in which you want to recover files) and copy the following content:

import { cp, readFile, readdir } from "fs/promises";

const dirs = await readdir("/Users/kapui/Documents/History");
for (const dir of dirs) {
  try {
    const entries = JSON.parse(
      await readFile(`/Users/kapui/Documents/History/${dir}/entries.json`, {
        encoding: "utf-8",
      })
    );
    const resource = entries.resource;
    const id = entries.entries.at(-1).id;
    if (!resource.startsWith("file:///Users/kapui/Documents/Coding/"))
      continue;
    await cp(`/Users/kapui/Documents/History/${dir}/${id}`, new URL(resource));
    console.log(`Copied ${dir}/${id} to ${resource}`);
  } catch (e) {
    console.log(e);
  }
}

Make sure to change the username. The above paths are for macOS, so if you are on Windows or Linux, you should change them to where VSCode data is stored. The if (!resource.startsWith("file:///Users/kapui/Documents/Coding/")) continue; part can be replaced with any condition to filter the files you wish to restore. (In this case, I only want to restore files in the folder I deleted: file:///Users/kapui/Documents/Coding/)

You may then run the script. After that, many of your files will be back. Please note that any file that you have never modified will not be restored. You might see files that you have already (intentionally) deleted or moved restored, so there is still some work to be manually done.

The best way to prevent this whole situation is to regularly backup your projects, or use a version manager like Git.