Introduction to vs code plug-in development (2)

  • 1、 Preface

stayLast articleIn this paper, I briefly introduced the basic process of vscode plug-in development, and explained how to obtain the absolute path of the folder and the method of user input. Recently, a new plug-in has been developed to replace the contents of the currently edited file. Google has made a circle and found that there are few articles about this. I’d like to make a record here, hoping to help people with similar needs.

  • 2、 Demand

The requirements are very simple. I need to change the contents of the following file:

export default {

Replace with:

export default {
    add_member: 'ce0',
    manage_member_card: 'ce1',
    member_setting: 'ce2',
    search_member: 'ce3',
    edit_member: 'ce4',
    delete_member: 'ce5',
    assign_consultant: 'ce6',
    add_member_tag: 'ce7',
    import_member: 'ce8',
    modify_member_point: 'ce9',

It can be understood as a simple automatic numbering tool. There are three main problems to be solved

  • Gets the current file path
  • Read file content
  • Write file content

Here’s how to do it.

  • 3、 Implementation

At first, I thought that vscode had a ready-made API to retrieve the contents of the current file, but I couldn’t find it in a circle, so I had to implement it in a circuitous way.

The first step is to obtain the path of the current file

const currentlyOpenTabfilePath = vscode.window.activeTextEditor.document.fileName;

Second, read the contents of the file and split it into arrays

const fs = require('fs');

const fileContentArr = fs.readFileSync(currentlyOpenTabfilePath, 'utf8').split(/\r?\n/);

The third step is to write a file. Because the contents of the file cannot be replaced line by line, we can only empty the original file and add it back line by line.


fileContentArr.forEach( (line, index) => {
    let content = line;
    if (line.slice(-1) == '#') {
        content = xxxxx;

    fs.appendFileSync(currentlyOpenTabfilePath, content + ((index == contentLength - 1) ? '' : '\n'));
  • 4、 Summary

In fact, the realization of this requirement is quite simple, mainly based on the characteristics of vscode. If there is a better way to achieve it, please leave me a message