fs.readdirSync的奇怪行为

时间:2016-03-03 03:51:44

标签: javascript node.js npm synchronization pm2

我使用nodejs 5.5.0和pm2 1.0.1。我运行脚本:

npm start

在package.json中,它被定义为:

"scripts": {
    "start": "pm2 start bin/www --watch"
},

我有这个简单的脚本,它返回一个视频列表并且有效:

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
    const fs = require('fs');
    shows = fs.readdirSync(`public/videos`);
    res.render('index', shows);
});

module.exports = router;

但是我观察到一些有趣的事情......如果我做了以下修改,它就不再有用了,并返回一个空列表:

//shows = fs.readdirSync(`public/videos`);
res.render('index', fs.readdirSync(`public/videos`));

为了使它更有趣,以下工作:

shows = fs.readdirSync(`public/videos`);
res.render('index', fs.readdirSync(`public/videos`));

在我看来,如果有某种延迟或缓存,fs.readdirSync工作正常,但如果在同一行直接调用则不行。

我是否想念一些简单的事情?

2 个答案:

答案 0 :(得分:1)

如果我错了,有人会纠正我。

但我相信这是因为<!DOCTYPE html> <html> <head prefix= "og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# product: http://ogp.me/ns/product#"> <meta property="og:type" content="og:product" /> <meta property="og:title" content="The Smashing Pack" /> <meta property="og:description" content="A smashing pack full of items!" /> <meta property="og:image" content="http://www.friendsmash.com/images/pack_600.png" /> <meta property="og:url" content="http://www.friendsmash.com/og/smashingpack.html" /> <meta property="product:price:amount" content="2.99"/> <meta property="product:price:currency" content="USD"/> <meta property="product:price:amount" content="1.99"/> <meta property="product:price:currency" content="GBP"/> </head> </html> 有第三个参数,你不知道哪个是res.render noted here

因此,当您在第一个示例中创建变量时,将阻塞直到获得变量,然后使用运行时可用的变量渲染模板。

但是在你的第二个例子中,你传递了这个选项,但是callback的回调是在res.render完成填充之前调用的。

答案 1 :(得分:1)

我想通了,实际上我错过了一些非常简单的东西。 本地变量的名称为重要

在案例3中,虽然未明确传入节目,但实际上使用swig呈现的页面可以看到它。

如果我不想介绍变量节目,我可以完成以下工作:

res.render('index', {shows: fs.readdirSync('public/videos')});
相关问题