javascript - formating a list of files in directory in JSON format -


i required list files in directory in json format passed on jade template. how can asynchronously?

router.get('/', function(req, res, next) {   res.render('index', {     title: 'advanced solution writer',     pdf: json.parse( /*need files inside directory foo*/)});  }); 

can write anonymous function returns list of files in it? here piece of code tried not working. new node.js

router.get('/', function(req, res, next) {   res.render('index', {     title: 'advanced solution writer',     pdf: json.parse(          function() {           const fs = require('fs');           fs.readdir("./public/pdf", function (err, files) {             if (err) {               console.log(err);             }             return files;           })         }     )});  }); 

you're doing inside out. asynchronous approach requires start reading file list, , in callback, can render page.

roughly this:

const fs = require('fs');  router.get('/', function(req, res, next) {   fs.readdir("./public/pdf", function (err, files) {     if (err) {       console.error(err);       throw err; // generate 500 internal server error     }     res.render('index', {       title: 'advanced solution writer',       pdf: json.parse(files)     });   }); }); 

i recommend looking promises alternative callbacks. promises can make flow of code clearer , simpler.


Comments