简体   繁体   中英

How to get argument from inside an inner function in a node.js route to below scope

I obtained the code below from the NPM package node-dir, The code works fine as it reads a directory and than reads each file in the directory and spits it back out to the console. What I really want is for it to be sent with JSON.stringify so I can than perform an ajax or $.getJSON call to render it to the UI so I can build reports from the data.

I get where the issue is, the files argument is inside of the second functions scope. So when I try to perform the req.send with files it says files is undefined. If I try to put req.send inside of the function it will say req is not defined, or if I pass in req as an argument it will say req.send is not a function because the function is stored with in router.get.

Im hoping for a simple solution with the current code or is there a better approach? I believe it may have something to do with .apply() or possibly some kind of callback or promise maybe? Sorry im still a noob with this kind of functional programming.

router.get("/api/all/reports", (req, res) => {
     const pathToDir = path.resolve(__dirname, "../../", "automation_projects/fcsf/results/");
    dir.readFiles(pathToDir,
       function(err, content, next) {
           if (err) throw err;
           console.log('content:', content);
           next();
          res.send(JSON.stringify(content));
       },
       function(err, files){
           if (err) throw err;
       });

    });
router.get("/api/all/reports", (req, res) => {
     let fileContent = "";
     const pathToDir = path.resolve(__dirname, "../../", "automation_projects/fcsf/results/");
    dir.readFiles(pathToDir,
       function(err, content, next) {
           if (err) throw err;
           console.log('content:', content);
           fileContent += content; 
           next()
       },
       function(err, files){
           if (err) throw err;
           res.send(JSON.stringify(fileContent));
       });

    });

Please let me know if it's working. I think it should be res.send or res.json (not mandatory)

please be careful with large file content. You need to use res.pipe or any streaming functionality for that

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM