我想调用这个异步回调函数:
var glob = require('glob');
var globResults = undefined;
function globAsync(callback) {
glob('*.jpg', { cwd: 'public/portfolio/weddings/', sort: true }, function (err, files) {
var results = JSON.stringify(files);
globResults = results;
callback();
});
};
function globCaller() {
var g = globResults;
console.log('STRING: ' + g);
return g;
};
globAsync(globCaller); // This will init globCaller()
在这个Node.js路由器中:
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('portfolio', {
layout: 'main',
centering: true,
titleShown: false,
title: 'Hi!',
description: 'Home page of Lantos Istvan Photography',
keywords: 'wedding,photography,film,lantos,istvan',
bodyClass: 'horizontal',
imagesFolder: '\/portfolio\/weddings\/',
images: globCaller()
});
});
我希望在上面的例子中显示images:
后的预期输出(这在控制台中显示):
["image-1.jpg","image-10.jpg","image-11.jpg","image-12.jpg"]
我该怎么做?
我也有这个把手文件:
{{#each images}}
<li><img src="{{../imagesFolder}}{{this}}.jpg" alt=""></li>
{{else}}
<p class="empty">No content</p>
{{/each}}
有时html输出中的渲染输出是:
<li><img src="/portfolio/weddings/image-1.jpg,image-10.jpg,image-11.jpg,..." alt="" /></li>
但我想:
<li><img src="/portfolio/weddings/image-1.jpg" alt="" /></li>
<li><img src="/portfolio/weddings/image-10.jpg" alt="" /></li>
<li><img src="/portfolio/weddings/image-11.jpg" alt="" /></li>
答案 0 :(得分:1)
在glob()的回调中使用res.render()而不是拥有所有全局变量更简单:
/* GET home page. */
router.get('/', function(req, res, next) {
glob('*.jpg', { cwd: 'public/portfolio/weddings/', sort: true }, function (err, files) {
var results = JSON.stringify(files);
res.render('portfolio', {
layout: 'main',
centering: true,
titleShown: false,
title: 'Hi!',
description: 'Home page of Lantos Istvan Photography',
keywords: 'wedding,photography,film,lantos,istvan',
bodyClass: 'horizontal',
imagesFolder: '\/portfolio\/weddings\/',
images: results
});
});
});
编辑:评论中讨论的替代解决方案
function globAsync(params, callback) {
glob(params.wildcard || '*.jpg', {
cwd: params.cwd || 'public/portfolio/weddings/',
sort: true
}, function(err, files) {
if (err) {
return callback(err);
}
// Do anything else with the results (files) if you need to here
callback(null, files); // null means no error, return results in callback
});
}
router.get('/', function(req, res, next) {
globAsync({
wildcard: '*.jpg', // use default in globAsync if not passed in
cwd: 'public/portfolio/weddings/' // use default in globAsync if not passed in
}, function(err, results) {
if (err) {
return res.send(err);
}
res.render('portfolio', {
layout: 'main',
centering: true,
titleShown: false,
title: 'Hi!',
description: 'Home page of Lantos Istvan Photography',
keywords: 'wedding,photography,film,lantos,istvan',
bodyClass: 'horizontal',
imagesFolder: '\/portfolio\/weddings\/',
images: results
});
});
});