简体   繁体   English

这是使用node.js和jade在目录中列出文件的方法

[英]Is this the way to list a file in directory using node.js and jade

I am trying to list a file in a directory using jade and node.js but I am not sure if below is the right way of doing it, as I receive a type error that says 我试图使用jade和node.js在目录中列出一个文件,但我不确定下面是否是正确的方法,因为我收到一个类型错误,说

Cannot read property 'length' of undefined

Any hint would be much appreciated 任何提示都将非常感激

h1 Your tasks
p


// list all the file
ul
  for file in files
    li
      p= file

node.js code node.js代码

app.get('/tasks', function(req, res){


  fs.readdir('tasks/index', function(err, data){
    res.render('tasks/index', {"files": data});
  });

});

update 更新

app.get('/tasks', function(req, res){


  fs.readdir('tasks', function(err, data){
    res.render('tasks/index', {"files": data});
  });

});

error 错误

500 TypeError: /path/views/tasks/index.jade:7 5| // list all the file 6| ul > 7| each file in files 8| li 9| p= file 10| Cannot read property 'length' of undefined

    5| // list all the file
    6| ul
    > 7| each file in files
    8| li
    9| p= file
    10|
    Cannot read property 'length' of undefined

OK, several issues: 好的,有几个问题:

  1. You need to use each file in files instead of for 您需要使用each file in files ,而不是for
  2. 'tasks/index' is being treated as both a directory and a file. 'tasks / index'被视为目录和文件。 It can't be both, and it's probably a file, so your readDir call is probably throwing an error which is why data (and thus files ) is undefined. 它不能同时存在,并且它可能是一个文件,因此readDir调用可能会引发错误,这就是data (以及files )未定义的原因。
  3. fs.readDir is going to treat relative paths as relative to process.cwd whereas res.render treats relative paths relative to express's 'views' setting. fs.readDir将相对路径视为相对于process.cwd,而res.render则相对于express的'views'设置处理相对路径。
  4. Ignoring the error thrown by step 3 is just making your life harder, which is why it's a bad habit. 忽略第3步抛出的错误只会让你的生活更加艰难,这就是为什么这是一个坏习惯。

fs.readdir(__dirname + '/views/tasks', function(error, data){
  if (error) {
      res.status(500).send(error);
      return;
  }
  res.render('tasks/index', {"files": data});
});

I don't know your filesystem organization entirely, so the paths are just guesses, but the root of your problem seems to be not coding properly in terms of filesystem organization. 我完全不知道你的文件系统组织,所以路径只是猜测,但问题的根源似乎是在文件系统组织方面没有正确编码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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