首页 > 解决方案 > 如何使用递归函数写入多个文件

问题描述

我想在一次调用中写入文件,但我无法循环创建路径。

async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}

如果我使用条件创建新文件,对许多声明

asyncForEach(items, async (element) => {    
        if(element.hasOwnProperty('item')){
            const path = 'tests/'+element.name;
            console.log(path);
            fs.mkdirSync(path, { recursive: true })
            // await waitFor(50)
            asyncForEach(element.item, async (second) => {
                const second_path = path
                if(second.hasOwnProperty('item') == false){
                    // console.log(second.name)
                    write(second, path, contents)

这是输入 JSON

{
    "info": {
        "_postman_id": "fcf35761-60a4-44e8-adf9-cb871a823e38",
        "name": "Reqres In",
        "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
    },
    "item": [
        {
            "name": "Users",
            "item": [
                {
                    "name": "LIST USERS",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "id": "17155c09-d1cd-467c-8d45-94d2c0f7d728",
                                "exec": [
                                    "pm.test(\"Status code is 200\", function () {",
                                    "    pm.response.to.have.status(200);",
                                    "});"
                                ],
                                "type": "text/javascript"
                            }
                        }
                    ],
                    "request": {
                        "method": "GET",
                        "header": [],
                        "url": {
                            "raw": "{{URL}}/api/users",
                            "host": [
                                "{{URL}}"
                            ],
                            "path": [
                                "api",
                                "users"
                            ]
                        }
                    },
                    "response": []
                },
                {
                    "name": "SINGLE USER",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "id": "3b1d6983-204f-4da7-a901-4ee4bfd6b69d",
                                "exec": [
                                    "pm.test(\"Status code is 201\", function () {",
                                    "    pm.response.to.have.status(200);",
                                    "});"
                                ],
                                "type": "text/javascript"
                            }
                        }
                    ],
                    "request": {
                        "method": "GET",
                        "header": [],
                        "url": {
                            "raw": "{{URL}}/api/users/2",
                            "host": [
                                "{{URL}}"
                            ],
                            "path": [
                                "api",
                                "users",
                                "2"
                            ]
                        }
                    },
                    "response": []
                },
                {
                    "name": "SINGLE USER NOT FOUND",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "id": "9e63a01c-a60a-4ac8-ac25-2e2d99614781",
                                "exec": [
                                    "pm.test(\"Status code is 404\", function () {",
                                    "    pm.response.to.have.status(404);",
                                    "});"
                                ],
                                "type": "text/javascript"
                            }
                        }
                    ],
                    "request": {
                        "method": "GET",
                        "header": [],
                        "url": {
                            "raw": "{{URL}}/api/users/23",
                            "host": [
                                "{{URL}}"
                            ],
                            "path": [
                                "api",
                                "users",
                                "23"
                            ]
                        }
                    },
                    "response": []
                }
            ],
            "protocolProfileBehavior": {}
        },
        {
            "name": "Create",
            "item": [
                {
                    "name": "CREATE",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "id": "35b3b52e-3dfa-4503-8437-1c826a60f283",
                                "exec": [
                                    "pm.test(\"Status code is 200\", function () {",
                                    "    pm.response.to.have.status(200);",
                                    "});"
                                ],
                                "type": "text/javascript"
                            }
                        }
                    ],
                    "request": {
                        "method": "POST",
                        "header": [],
                        "body": {
                            "mode": "raw",
                            "raw": "{\n    \"name\": \"john doe\",\n    \"job\": \"leader\"\n}",
                            "options": {
                                "raw": {
                                    "language": "json"
                                }
                            }
                        },
                        "url": {
                            "raw": "{{URL}}/api/users",
                            "host": [
                                "{{URL}}"
                            ],
                            "path": [
                                "api",
                                "users"
                            ]
                        }
                    },
                    "response": []
                },
                {
                    "name": "UPDATE - PUT",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "id": "34b75157-7d92-486b-80fc-f14ffbde2870",
                                "exec": [
                                    "pm.test(\"Status code is 200\", function () {",
                                    "    pm.response.to.have.status(200);",
                                    "});"
                                ],
                                "type": "text/javascript"
                            }
                        }
                    ],
                    "request": {
                        "method": "PUT",
                        "header": [],
                        "body": {
                            "mode": "raw",
                            "raw": "{\n    \"name\": \"morpheus\",\n    \"job\": \"zion resident\"\n}",
                            "options": {
                                "raw": {
                                    "language": "json"
                                }
                            }
                        },
                        "url": {
                            "raw": "{{URL}}/api/users/2",
                            "host": [
                                "{{URL}}"
                            ],
                            "path": [
                                "api",
                                "users",
                                "2"
                            ]
                        }
                    },
                    "response": []
                }
            ],
            "protocolProfileBehavior": {}
        },
        {
            "name": "Registrasi",
            "item": [
                {
                    "name": "Registrasi Success",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "id": "e1ca180d-406b-4577-bdff-bfa90409e3b0",
                                "exec": [
                                    "pm.test(\"Status code is 200\", function () {",
                                    "    pm.response.to.have.status(200);",
                                    "});"
                                ],
                                "type": "text/javascript"
                            }
                        }
                    ],
                    "request": {
                        "method": "POST",
                        "header": [],
                        "body": {
                            "mode": "raw",
                            "raw": "{\n    \"email\": \"{{email}}\",\n    \"password\": \"pistol\"\n}",
                            "options": {
                                "raw": {
                                    "language": "json"
                                }
                            }
                        },
                        "url": {
                            "raw": "{{URL}}/api/register",
                            "host": [
                                "{{URL}}"
                            ],
                            "path": [
                                "api",
                                "register"
                            ]
                        }
                    },
                    "response": []
                },
                {
                    "name": "Registrasi Failed",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "id": "83cad3df-b243-4822-a359-5881a8573319",
                                "exec": [
                                    "pm.test(\"Status code is 400\", function () {",
                                    "    pm.response.to.have.status(400);",
                                    "});"
                                ],
                                "type": "text/javascript"
                            }
                        }
                    ],
                    "request": {
                        "method": "POST",
                        "header": [],
                        "body": {
                            "mode": "raw",
                            "raw": "{\n    \"email\": \"sydney@fife\"\n}",
                            "options": {
                                "raw": {
                                    "language": "json"
                                }
                            }
                        },
                        "url": {
                            "raw": "{{URL}}/api/register",
                            "host": [
                                "{{URL}}"
                            ],
                            "path": [
                                "api",
                                "register"
                            ]
                        }
                    },
                    "response": []
                }
            ],
            "protocolProfileBehavior": {}
        },
        {
            "name": "Login",
            "item": [
                {
                    "name": "LOGIN - SUCCESSFUL",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "id": "510fc7b5-3a1f-41c4-932f-c7865c693aa6",
                                "exec": [
                                    "pm.test(\"Status code is 200\", function () {",
                                    "    pm.response.to.have.status(200);",
                                    "});",
                                    "",
                                    "var jsonData = JSON.parse(responseBody);",
                                    "pm.environment.set(\"token\", jsonData.token);"
                                ],
                                "type": "text/javascript"
                            }
                        }
                    ],
                    "request": {
                        "method": "POST",
                        "header": [],
                        "body": {
                            "mode": "raw",
                            "raw": "{\n    \"email\": \"eve.holt@reqres.in\",\n    \"password\": \"cityslicka\"\n}",
                            "options": {
                                "raw": {
                                    "language": "json"
                                }
                            }
                        },
                        "url": {
                            "raw": "{{URL}}/api/login",
                            "host": [
                                "{{URL}}"
                            ],
                            "path": [
                                "api",
                                "login"
                            ]
                        }
                    },
                    "response": []
                },
                {
                    "name": "LOGIN - UNSUCCESSFUL",
                    "event": [
                        {
                            "listen": "test",
                            "script": {
                                "id": "4bb57fea-29ab-4e61-a21c-deb0b2a9cd9a",
                                "exec": [
                                    "pm.test(\"Status code is 400\", function () {",
                                    "    pm.response.to.have.status(400);",
                                    "});"
                                ],
                                "type": "text/javascript"
                            }
                        }
                    ],
                    "request": {
                        "method": "POST",
                        "header": [],
                        "body": {
                            "mode": "raw",
                            "raw": "{\n    \"email\": \"peter@klaven\"\n}",
                            "options": {
                                "raw": {
                                    "language": "json"
                                }
                            }
                        },
                        "url": {
                            "raw": "{{URL}}/api/login",
                            "host": [
                                "{{URL}}"
                            ],
                            "path": [
                                "api",
                                "login"
                            ]
                        }
                    },
                    "response": []
                }
            ],
            "protocolProfileBehavior": {}
        }
    ],
    "protocolProfileBehavior": {}
}

标签: javascriptnode.jsrecursion

解决方案


我想这是你不想要的,当遇到目录时递归添加路径,当它是叶节点时写入文件,虽然不知道你的逻辑细节,这是一个演示代码,只是为了阐明如何将你的代码转换为递归模型.

请检查,任何更多问题留下您的评论:

    async doFileWriteJob(array, path) {  
    for (let index = 0; index < array.length; index++) {
        element = array[index]
        if(element.hasOwnProperty('item')){
            if(!path) {
                path = 'tests'
            } else {
                path = path + '/' + element.name;
            }
            console.log(path);
            if(element.item && element.item.length > 0) {
                fs.mkdirSync(path, { recursive: true })
                // await waitFor(50)
                doFileWriteJob(element.item, path)
                
            } else {
                if(element.hasOwnProperty('item') == false){
                    // console.log(element.name)
                    write(element, path, element.contents)
                }
            }
        }
    }
})

doFileWriteJob(array, '');

推荐阅读