javascript - 我如何将数据物理添加到数组中?
问题描述
So i'm using this website called Glitch to host a discord bot. However, this is the first time i need to store data physically so if there ever is a downtime, all the data i've inserted while the program was running won't be lost.
For this, i initially thought of using databases, but it simply looks too complex, so i decided to make the program edit a file and add the data there. However, i found no way to retrieve that data since glitch doesn't allow you to reference variables from other files, an, even if it did, it would have no way to find it since the data cannot be stored in an array.
So my question is, if i were to use fs, how could i actually add the data into an array to retrieve it later? and if not, could someone please guide me through how to setup and add this data i've talked about before in a (free) database?
例子:
let array1 = ["1, 2, 3", "4, 5, 6"]
//How can i physically add data to this array so that it shows up in the editor and can be retrieved later?
我试图尽可能多地解释这一点,但我不知道是否清楚我想要做什么。如果没有,请给我留言。
解决方案
如果这就是你所需要的,那么你可以很容易地在 node.js 中读取和写入一个数组,如下所示:
const fsp = require('fs').promises;
async function readData(fname) {
let data = await fsp.readFile(fname);
return JSON.parse(data);
}
function writeData(fname, data) {
return fsp.writeFile(fname, JSON.stringify(data));
}
这两个函数都返回一个 Promise,所以你可以像这样使用它们:
let d = [1,2,3,4,5];
writeData("somefile.json", d).then(() => {
console.log("data written to file successfully");
}).catch(err => {
console.log(err);
});
而且,稍后(在上述写入完成后),您可以读取数据:
readData("someFile.json").then(data => {
console.log(data);
// use the data here
}).catch(err => {
console.log(err);
});
推荐阅读
- json - Ansible:使用 --extra-vars 时 JSON 无效
- laravel - 如何使用 Laravel 的验证助手对有效持续时间进行功能测试?
- mysql - PHP OOP INSERT INTO 仅在数据库中插入 NULL
- python - SQLAlchemy - 继承列的不同名称
- c++ - noexcept(auto) 自动推断函数是否可以声明 noexcept
- mysql - 如何将 MySQL 转储转换为 SQL Server 格式
- adobe - 在 Acrobat 中检查已删除的项目
- javascript - 如何在 React 中全局共享库?
- java - java中的坐标验证
- jenkins - 在另一个 java 管道项目中引用库时,在共享库中定义的 @Grab 不起作用