是否有机会将 map 方法作为对象数组输出到变量中?

Is there any chance to output map method into variable as an array of objects?

大家好!

我想将用户作为文件存储在文件夹中,文件名等于 user_id。

data
| - users
      | - afdcab7e-b595-4a15-be0f-5f0337bd1317.json
      | - fdfacb7i-bk00-4a15-be0f-5f0337b1d991.json

例如每个用户都有自己的数据

{
    "_id": "afdcab7e-b595-4a15-be0f-5f0337bd1317",
    "email": "test1@test.pl",
    "password": "a$nIoudV7eXmJbU7e/P6YCbOccUkTbp8tcQKhyCEfmNOLihrW6QqPTC"
}
{
    "_id": "fdfacb7i-bk00-4a15-be0f-5f0337b1d991",
    "email": "test2@test.pl",
    "password": "a$nIoudV7eXmJbU7e/P6YCbOccUkTbp8tcQKhyCEfmNOLihrW6QqPTC"
}

然后我想读取所有文件的内容,然后将对象放入一个临时数组中。

exports.indexSignin = (req, res) => {

    fs.readdir('./data/users', (err, files) => {
        if (err) console.log(err);

        const obj = [];
        files.map((file) => {
            fs.readFile(`./data/users/${file}`, 'utf-8', (err, data) => {
                if (err) console.log(err);
                obj.push(JSON.parse(data))
                console.log(obj)
            });
        });
        console.log(obj) //There obj is empty but I want an array
    });

    res.render('./index/index');
});

作为输出,我希望将一个数组保存到变量中,如下所示:

[
{
    "_id": "afdcab7e-b595-4a15-be0f-5f0337bd1317",
    "email": "test1@test.pl",
    "password": "a$nIoudV7eXmJbU7e/P6YCbOccUkTbp8tcQKhyCEfmNOLihrW6QqPTC"
},
{
    "_id": "fdfacb7i-bk00-4a15-be0f-5f0337b1d991",
    "email": "test2@test.pl",
    "password": "a$nIoudV7eXmJbU7e/P6YCbOccUkTbp8tcQKhyCEfmNOLihrW6QqPTC"
}
]

您对如何在外部使用映射数据或将其重构为更好的方式有任何想法吗?

这与我的代码相同。希望对你有帮助。

const { readdir, readFile } = require("fs/promises");

const readFiles = async () => {
    try {
        const path = "./test"
        const files = await readdir(path);
        console.log(files)

        const fileAwaits = files.map(file => readFile(`${path}/${file}`, "utf8"))
        const contents = await Promise.all(fileAwaits)
        console.log(contents.map(co => JSON.parse(co)))
    } catch (err) {
        console.error(err)
    }
}

readFiles()

因此,如果您想在 API 处理程序中使用它,请将其更改为以下内容:

exports.indexSignin = async (req, res) => {

    try {
        const path = "./test" // replace path by your own
        const files = await readdir(path);
        console.log(files)

        const fileAwaits = files.map(file => readFile(`${path}/${file}`, "utf8"))
        const contents = await Promise.all(fileAwaits)
        const arrayContent = contents.map(co => JSON.parse(co))
        console.log(arrayContent);
    } catch (err) {
        console.error(err)
    }
    res.render('./index/index');
});

谢谢你们! 我在您的帮助下解决了我的问题。

这是我需要的一个工作示例:

exports.indexSignin = (req, res) => {

    const readFiles = async () => {
        try {
            const path = "./data/users"
            const files = await readdir(path);
    
            const fileAwaits = files.map(file => readFile(`${path}/${file}`, "utf8"))
            const contents = await Promise.all(fileAwaits)
            return contents.map(co => JSON.parse(co))
        } catch (err) {
            throw err;
        }
    }

    readFiles()
        .then(test => console.log(test))
        .catch(err => console.log('Directory not found.'))
        .finally(() => console.log('Rest of the code...'));

    res.render('./index/index');


    // or IIFY which do the same 
    (async () => {
        try {
            const test = await readFiles();
            console.log(test);
        } catch (err) {
            console.log('Directory not found.');
        }
        console.log('Rest of the code...')
        res.render('./index/index');
    })()
};