【问题标题】:Fs file handler for api用于 api 的 Fs 文件处理程序
【发布时间】:2021-09-15 19:05:26
【问题描述】:

所以我想创建一个路由文件夹,其中包含包含路由的子文件夹,但我不知道如何使用 fs...

我只知道如何在路由文件夹中获取文件,而不是在子文件夹中

这是我的文件处理程序代码

const { readdirSync } = require('fs');


module.exports = function(app){
    readdirSync(__dirname).forEach(function(file) {
        if (file == "index.js") return;
        var name = file.substr(0, file.indexOf('.'));
        const route = require('./' + name)
                app.get(`/${route.name}`, async (req, res) => {
                route.run(req, res)                    
                })
    });
}

它从路由文件夹中获取文件

-routes
  |__index.js
  |__route.js
  |__route.js

我想让它从子文件夹中获取路由

-routes
  |__index.js
  |
  |__image routes
     |__route1.js

我在网上找不到任何帮助...

【问题讨论】:

    标签: javascript node.js api fs


    【解决方案1】:

    如果你不介意使用外部库,我推荐使用glob

    你想要做的事情可以通过一个函数调用来实现:

    const glob = require("glob");
    
    glob("**/*.js", {cwd: __dirname}, (error, matches) => {
        if (error) return;
        console.log(matches);
    })
    

    这对给定目录中的许多文件使用 glob 模式,返回整个路径,例如:image-routes/route1.jsindex.js 等。

    【讨论】:

    • 好的,所以现在我遇到了一个 smol 问题,这很有效,但我想将子文件夹和文件分开,这样我就可以像foldername/filename 这样的路由我怎么能这样做事物? 我不是要代码只是如何做到这一点
    • 您可以尝试对字符串matches[index].split("/")调用拆分函数
    猜你喜欢
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2022-10-09
    • 1970-01-01
    • 2012-09-20
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多