简体   繁体   中英

How should you store a multi-line text file? As a text file or js file?

I am building a discord bot using discord.js and NodeJS. I have multi-line (about 20 lines long) message that I wish to send to a channel for a certain command. For improving the readability of the source code, I thought that I would use a different file for storing this message. Initially, I thought I would move the contents to a text file and then use fs.readFile() to read the contents. But, now, I think it's better to store the contents in a variable (lets say multiLineString in another js file (say message.js and export this variable from the file. That way, I could directly get the contents using require('./message.js').multiLineString . But I don't know if this is a good practice as I am new in NodeJS. So, which is the correct or better method, in terms of both memory and performance?

You should consider storing these messages in JSON files. (go read about JSON). They're safer than pure Javascript for this purpose: You have to totally trust the content of files you require() . But files you read and then do JSON.parse() on will just make that function throw an error if they're wrong.

The real question here is, whether you want to be able to edit that message on purpose (without having to restart your server) - or not.

If not, there's nothing really wrong with any approaches you mentioned. The only thing that you'd rather avoid is rereading the text on each request (especially with a synchronous operation). Slightly more time will be spent on converting the text read from a file system into a proper JS value, but that's really negligible.

However, if message itself should be dynamic and you want to be able to update it without having your server restarted, that's different. And if that's the case, strive for how easy is for admin to work with that file, not for how performant the operation is; you'll have to spend time on reading this anyway. The best you can do is to check some kind of 'fast' marker - for example, update time (if we still talk about the files) - before actually attempting to reread it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM