You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Discord Bot中将JavaScript对象写入JSON文件的数组?

实现Discord机器人将歌曲添加到JSON数据库

问题描述

我正在开发Discord机器人,用户使用/add命令时,机器人会要求输入必填的name(歌曲名)和artist(歌手)参数,这两个参数组成歌曲对象。我需要每次执行该命令时,把这个对象添加到data.json文件的数组里,方便后续随机获取。

现有代码

命令文件(JavaScript)

module.exports = {
  data: new SlashCommandBuilder()
    .setName('add')
    .setDescription('Add a song to the database.')
    .addStringOption(option =>
      option.setName('artist')
        .setDescription('The artist of the song')
        .setRequired(true))
    .addStringOption(option =>
      option.setName('name')
        .setDescription('The name of the song')
        .setRequired(true)),

  async execute(interaction) {
    let name = interaction.options.getString('name');
    let artist = interaction.options.getString('artist');
    
    const data = { name: name, artist: artist};

    await interaction.reply(`**${artist}** - **${name}** was added to the database.`)
  },
};

数据库文件(data.json)

[
    {
        "name":"Die for You",
        "artist":"The Weeknd"
    },
    {
        "name":"FEAR",
        "artist":"Kendrick Lamar"
    }
]

实现步骤

要完成添加功能,需要通过Node.js的文件系统模块读写JSON文件,具体步骤如下:

  • 引入异步文件操作模块fs/promises和路径处理模块path
  • 读取data.json内容并解析为JavaScript数组
  • 将新歌曲对象推入数组
  • 将更新后的数组重新写入JSON文件
  • 捕获操作中的异常,避免机器人崩溃并给用户反馈

修改后的execute函数代码

const fs = require('fs/promises');
const path = require('path');

async execute(interaction) {
  let name = interaction.options.getString('name');
  let artist = interaction.options.getString('artist');
  
  const newSong = { name: name, artist: artist};

  try {
    // 获取data.json的绝对路径,避免跨平台路径问题
    const filePath = path.join(__dirname, 'data.json');
    
    // 读取并解析JSON文件
    const fileContent = await fs.readFile(filePath, 'utf8');
    const songs = JSON.parse(fileContent);
    
    // 添加新歌曲到数组
    songs.push(newSong);
    
    // 写入更新后的数组,格式化JSON保证可读性
    await fs.writeFile(filePath, JSON.stringify(songs, null, 2), 'utf8');
    
    await interaction.reply(`**${artist}** - **${name}** 已成功添加到数据库。`)
  } catch (error) {
    console.error('更新数据库出错:', error);
    await interaction.reply('添加歌曲失败,请稍后重试。');
  }
},

注意事项

  • 路径处理:使用path.join()确保在Windows、Linux等不同系统下都能正确找到data.json文件
  • 异步操作:所有文件操作都用await等待完成,保证执行顺序正确
  • 错误处理:通过try-catch捕获文件读写、JSON解析中的异常,及时反馈给用户并记录错误日志

内容的提问来源于stack exchange,提问作者maruan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 23:15:44