fs.writeFile not creating a file

Hey, I am programming my own discord bot.
With the following code, I wanted to create a data file. However, it does not generate the file (at least it does not become visible). But also not generate the file

fs.writeFile(‘userdata.json’, ‘Hello content!’, function (err) {
if (err) throw err;
console.log(‘Saved!’);
});

Does anyone know why this happens? Please let me know.

WOAH WOAH WOAH

@code-alt has been summoned!

FS should NEVER be used in a discord bot. I just want to point out that when the user types in the command, it would rewrite the whole file.

Anyways, you should have required fs (it’s built in with node.js, you don’t need to install any other packages)

and it should be this:

fs.writeFile('/userdata.json', 'The content', function (err) {
if (err) throw err;
console.log('Saved!');
});

You shouldn’t have backticks, instead use quotes or the little line (’)

Hey.
First of al, Thanks for your reply.
My code worked afterall. But i was too stupid to not refresh my project, only refreshed the page.

The backticks also were correcht because the file names will be a variable.

However, thanks for the help!

3 Likes

That’s bit of an exaggeration, there’s nothing wrong in adding fs to a Discord bot, it’s certainly less dangerous than an eval command, as long as the user knows the risk of exposing a bot command that uses fs to other users or if it’s an important file for the bot like the package.json file. And it’s a common practice to use fs to edit certain files based on the commands you’re running. But if the command allows you to edit whatever files you specify, then THAT is dangerous, not adding fs to a bot.

Relatively, the warning of fs usage in a Discord bot that you gave sounds like it’s more dangerous than exposing your bot token publicly. Hope you understand.

1 Like

This is an overstatement - writeFile or writeFileSync do work by completely rewriting the whole file, but there are other commands (appendFile, I think?) that simply write to the bottom of the file. The only caveat is sometimes you have to spam \n in the appending text.

But like what khalby said, using fs provides access to most of the file tree - don’t let the user pick what file they can write to. If they knew you were using glitch, they could easily nuke the packager and ENV files and cause a lot of headache.

Yeah like

lemme get

fs.writeFile('.env', 'TOKEN=tokenhere', callback);

and even change what the discord bot does

There’s fs.appendFile on this page.

Oh, cool! I’ll be using that in some of my projects :slight_smile:

1 Like