我有一个目录
view/tasks/index.jade
我想列出里面的所有文件,最初我有一个 node.js 文件的模板,它向任务添加字符串,任务页面将输出到目前为止的所有字符串输入,但是现在我想修改它以便我列出任务目录中的所有文件,除了 index.jade 和其他一些文件:我将列出所有其他文件。当我在下面运行我的修改时,它会返回一个类型错误。任何提示将不胜感激
app.get('/tasks', function(req, res){
Task.find({}, function (err, docs) {
res.render('tasks/index', {
title: 'Tasks index view',
docs: docs
});
});
// list file mod
fs.readdir('tasks/index', function(err, data){
res.render('tasks/index', {"files": data});
});
// list file mod
});
下面是我的 index.jade 文件
h1 Your tasks
p
a(href='/tasks/new', class='btn primary') Add a Task
- if(docs.length)
table
tr
th Task
th
each task in docs
tr
td #{task.task}
td
a.btn(href="/tasks/#{task.id}/edit") Edit
- else
p You don't have any tasks!
// list all the file
ul
for file in files
li
p= file
以下是我的错误
TypeError: /path/views/tasks/index.jade:22
20| // list all the file
21| ul
> 22| for file in files
23| li
24| p= file
25|
Cannot read property 'length' of undefined
at eval (eval at <anonymous> (path/node_modules/jade/lib/jade.js:166:8), <anonymous>:174:31)
at eval (eval at <anonymous> (/path/node_modules/jade/lib/jade.js:166:8), <anonymous>:217:4)
at Object.<anonymous> (path/node_modules/jade/lib
附加错误:
500 TypeError: /path/views/tasks/index.jade:22 20| // list all the file 21| ul > 22| for file in files 23| li 24| p= file 25| Cannot read property 'length' of undefined
20| // list all the file
21| ul
> 22| for file in files
23| li
24| p= file
25|
Cannot read property 'length' of undefined
at eval (eval at (/path/node_modules/jade/lib/jade.js:166:8), :174:31)
at eval (eval at (/path/node_modules/jade/lib/jade.js:166:8), :217:4)
at Object. (/path/node_modules/jade/lib/jade.js:167:35)
at ServerResponse.res._render (/path/node_modules/express/lib/view.js:422:21)
更新代码:
var async = require( 'async' );
app.get('/tasks', function(req, res){
var tasks, files;
async.series( [
// Find tasks
function ( callback ) {
Task.find({}, function (err, docs) {
tasks = docs;
callback();
});
},
// Find files
function ( callback ) {
fs.readdir('tasks/index', function(err, data){
files = data;
callback();
});
}
// Render and send response
], function ( error, results ) {
res.render('tasks/index', {
title: 'Tasks index view',
docs: tasks,
files: files
});
} );
});
app.get('/tasks/new', function(req, res){
res.render('tasks/new.jade', {
title: 'New task view'
});
});
app.post('/tasks', function(req, res){
var task = new Task(req.body.task);
task.save(function (err) {
if (!err) {
res.redirect('/tasks');
}
else {
res.redirect('/tasks/new');
}
});
});
app.get('/tasks/:id/edit', function(req, res){
Task.findById(req.params.id, function (err, doc){
res.render('tasks/edit', {
title: 'Edit Task View',
task: doc
});
});
});
app.put('/tasks/:id', function(req, res){
Task.findById(req.params.id, function (err, doc){
doc.updated_at = new Date();
doc.task = req.body.task.task;
doc.save(function(err) {
if (!err){
res.redirect('/tasks');
}
else {
// error handling
}
});
});
});