首页 > 解决方案 > 我如何将数据物理添加到数组中?

问题描述

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?

我试图尽可能多地解释这一点,但我不知道是否清楚我想要做什么。如果没有,请给我留言。

标签: javascriptnode.jsdatabasefilesystems

解决方案


如果这就是你所需要的,那么你可以很容易地在 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);
});

推荐阅读