自动注入代码片段
确认 VS Code 配置目录
- Windows: 
C:\Users\<用户名>\AppData\Roaming\Code\User\snippets\ - macOS: 
~/Library/Application Support/Code/User/snippets/ - Linux: 
~/.config/Code/User/snippets/ 
确保这些目录存在,并且你有权限读取和写入。如果目录不存在,可以手动创建。
编写 Node.js 脚本
以下是更新后的脚本,考虑了不同操作系统的路径:
const fs = require('fs');
const path = require('path');
const os = require('os');
// 定义代码片段
const snippet = {
  "My Custom Snippet": {
    "prefix": "mySnippet",
    "body": [
      "console.log('Hello, World!');",
      "const x = 42;",
      "console.log(`The value of x is ${x}`);"
    ],
    "description": "A custom snippet that logs a message and a variable."
  }
};
// 获取操作系统类型
const platform = os.platform();
// 根据操作系统设置 VS Code 用户代码片段文件路径
let snippetFilePath;
if (platform === 'win32') {
  snippetFilePath = path.join(process.env.APPDATA, 'Code', 'User', 'snippets', 'javascript.json');
} else if (platform === 'darwin') {
  snippetFilePath = path.join(process.env.HOME, 'Library', 'Application Support', 'Code', 'User', 'snippets', 'javascript.json');
} else if (platform === 'linux') {
  snippetFilePath = path.join(process.env.HOME, '.config', 'Code', 'User', 'snippets', 'javascript.json');
} else {
  throw new Error('Unsupported OS platform.');
}
// 确保目录存在
const snippetDir = path.dirname(snippetFilePath);
if (!fs.existsSync(snippetDir)) {
  fs.mkdirSync(snippetDir, { recursive: true });
}
// 读取现有的代码片段文件
fs.readFile(snippetFilePath, 'utf8', (err, data) => {
  let snippets = {};
  if (!err) {
    try {
      snippets = JSON.parse(data);
    } catch (e) {
      console.error('Failed to parse existing snippets file:', e);
    }
  }
  // 添加新的代码片段
  Object.assign(snippets, snippet);
  // 写回代码片段文件
  fs.writeFile(snippetFilePath, JSON.stringify(snippets, null, 2), 'utf8', (err) => {
    if (err) {
      console.error('Failed to write snippet file:', err);
    } else {
      console.log('Snippet added successfully!');
    }
  });
});
运行脚本
- 将上述代码保存为 
addSnippet.js文件。 - 在终端中运行以下命令来执行脚本:
 
node addSnippet.js
解释:
- 操作系统类型检测:使用 
os.platform()检测操作系统类型,并根据不同的操作系统设置正确的 VS Code 用户代码片段文件路径。 - 确保目录存在:在写入文件之前,确保目标目录存在,如果不存在则创建它。
 - 读取、解析、合并、写入:读取现有的代码片段文件,解析为 JSON 对象,合并新的代码片段,然后写回文件。
 - 获取目录路径:使用 
path.dirname(snippetFilePath)获取javascript.json文件所在的目录路径。 - 检查目录是否存在:使用 
fs.existsSync(snippetDir)检查目录是否存在。 - 创建目录:如果目录不存在,使用 
fs.mkdirSync(snippetDir, { recursive: true })创建目录。recursive: true选项确保所有父目录也会被创建。 
通过这种方式,你可以确保你的 Node.js 脚本能够在不同的操作系统上正确运行,并将代码片段注入到 VS Code 中。