[英]formating a list of files in directory in JSON format
I am required to list all files in a directory in JSON format which will be passed on to jade template. 我需要以JSON格式列出目录中的所有文件,这些文件将传递给jade模板。 How can I do that asynchronously?
我该如何异步进行?
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Advanced Solution Writer',
pdf: JSON.parse( /*need to get all files inside directory foo*/)});
});
Can I write something like anonymous function that returns list of files in it? 我可以编写类似匿名函数这样的东西来返回其中的文件列表吗? Here is a piece of code that I tried which is not working.
这是一段我尝试过的代码,它不起作用。 I am new to node.js
我是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;
})
}
)});
});
use res.render
inside the readdir
callback: 在
readdir
回调中使用res.render
:
var fs = require('fs');
router.get('/', function(req, res, next) {
fs.readdir("./public/pdf", function(err, files) {
if (err) {
console.log(err);
}
res.render('index', {
title: 'Advanced Solution Writer',
pdf: JSON.parse(files)
});
});
});
You're doing it inside out. 你是由内而外地做的。 The asynchronous approach requires you to start by reading the file list, and in the callback, you can render the page.
异步方法要求您先阅读文件列表,然后在回调中可以呈现页面。
Roughly like 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; // To generate a 500 internal server error
}
res.render('index', {
title: 'Advanced Solution Writer',
pdf: JSON.parse(files)
});
});
});
I also recommend looking into Promises as an alternative to callbacks. 我还建议研究Promises作为回调的替代方法。 Promises can make the flow of your code clearer and simpler.
承诺可以使您的代码流程更清晰,更简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.