0

I set up my discord BOT using node.js. For my advantage, I would need to store some data on a external file, but I don't seem to be able to access it from my index.js file (the main Bot file). I've tried having one static array in the external js/json files, but I can only retrieve undefined/empty values. Additionally, when I tried with a .txt file, once retrieved the content, I found it unable to call functions such as string.split().

Did I miss something in the package content perhaps?

4
  • 3
    We can't help you unless you show us the code you tried. Commented Mar 21, 2019 at 23:24
  • If you want to look at using a separate file, JSON might be able to help you there. It's a bit hard to know what you're trying to do, so edit your question and add some code. Commented Mar 22, 2019 at 7:34
  • I only need to basically store a list of predefined replies of the BOT, so I tried again with a simple .txt file and splitting the lines, and it works. Now I look like dumb but I swear yesterday my console was throwing me weird errors such as TypeError: text.split() is not a function... Commented Mar 22, 2019 at 12:39
  • Probably because it wasn't a string. .split(); can return an error like that if the thing you're trying to do it to isn't a string. Commented Mar 22, 2019 at 16:43

1 Answer 1

2

Assuming the data you are storing is in UTF-8 encoding:

var fs = require('fs');

fs.readFile('path/to/file', 'utf8', function(err, contents) {
    // code using file data
});

Assuming no errors contents will be a string of the data that is inside that file.

https://code-maven.com/reading-a-file-with-nodejs

Sign up to request clarification or add additional context in comments.

1 Comment

I was about to post the part of my code, but this snippet works like a charm with a .txt file, splitting the lines. Thanks very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.