Just a learner
Just a learner

Reputation: 28572

How to persist information for a vscode extension?

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?

Upvotes: 17

Views: 11709

Answers (3)

phil294
phil294

Reputation: 10852

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

Upvotes: 3

Manuel Spigolon
Manuel Spigolon

Reputation: 12880

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

Upvotes: 9

Gama11
Gama11

Reputation: 34138

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.

Upvotes: 32

Related Questions