How to persist information for a vscode extension?
Asked Answered
M

3

14

I'm planning to write a Visual Studio Code extension and it need to save some information for example a counter. The user can press a shortcut to increase or decrease the counter and the value of the counter will be saved some where. Next time when the user starts Visual Studio Code, the extension can load the counter's last value. My question is, where is the proper place to store this info?

Machiavellian answered 13/8, 2018 at 12:1 Comment(0)
S
27

You're probably looking for the Memento API. The ExtensionContext has two different memento instances you can access:

  • workspaceState

    A memento object that stores state in the context of the currently opened workspace.

  • globalState

    A memento object that stores state independent of the current opened workspace.

Both survive VSCode updates to my knowledge.

Sutherland answered 13/8, 2018 at 12:10 Comment(3)
I think some example would helpBedfordshire
Note that The value must be JSON-stringifyableDikdik
Is this the same data as defined in code.visualstudio.com/api/references/… ? e.g. writing to one of these APIs will change the config setting I set using the UI?Rollie
T
7

When you have a global state that you want to see across all your VSCODE windows, you can use the globalState from the extension's context.

I used this code in my extension to store a string:


async function activate (context) {
  const state = stateManager(context)
  
  const {
    lastPaletteTitleApplied
  } = state.read()

  await state.write({
    lastPaletteTitleApplied: 'foo bar'
  })

}


function stateManager (context) {
  return {
    read,
    write
  }

  function read () {
    return {
      lastPaletteTitleApplied: context.globalState.get('lastPaletteApplied')
    }
  }

  async function write (newState) {
    await context.globalState.update('lastPaletteApplied', newState.lastPaletteTitleApplied)
  }
}

Twittery answered 22/2, 2022 at 17:53 Comment(0)
R
1

You should use the state mementos, but if you need a folder instead to put custom stuff in, you can instead use storageUri https://code.visualstudio.com/api/references/vscode-api#ExtensionContext.storageUri and globalStorageUri

Roethke answered 31/5, 2024 at 21:16 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.