Skip to content
Advertisement

How to create a JS file with a command DISCORD.JS

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

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

module.exports = {
    name: 'createfile',
    run: async(client, message, args) => {
        var fileName = args[0]
        if(!args) {
            return message.reply('invalid name')
        };
        // Create file {fileName}.js
    }
}

Advertisement

Answer

Simply use the built-in fs module. It is built into node, so it doesn’t need to be installed via npm install.

const fs = require("fs");

// Synchronously create a new file:
fs.writeFileSync(`${__dirname}/${fileName}.js`, "<contents of JS file>");

See the official node docs for fs. This method sets the content of the file at the specified path, and creates the file if it doesn’t already exist. You can also use other similar methods, such as appendFileSync(), to create the file and/or modify its contents as well.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement