首页 > 解决方案 > Is there a way to create a JSON file using discord.js v12?

问题描述

I'm making a discord bot and I was wondering if you can create a JSON file with it. I haven't found a way to do it. My command reacts to &createfile {name} and it will always create a JSON file. My code so far:

const Discord = require('discord.js');

module.exports = {
    name: 'createfile',
    description: "The bot will create a .json file named after the argument",
    execute(message, args){
        var fileName = args[0]
        if(!args) {
            return message.reply('invalid name')
        };
        // Create file {fileName}.json
    }
}

Is there a way to create a file like that? Thanks :)

标签: javascriptjsondiscord.js

解决方案


You can create JSON files using fs

const Discord = require('discord.js');
const fs = require('fs');

module.exports = {
    name: 'createfile',
    description: "The bot will create a .json file named after the argument",
    execute(message, args){
        var fileName = args[0]
        if(!args) {
            return message.reply('invalid name')
        };
        
        let jsonFile = { 
          fileName: fileName
        };
 
        let data = JSON.stringify(jsonFile);
        fs.writeFileSync(`${fileName}.json`, data);
    }
}

推荐阅读