1

所以我决定重做一个博客并使用降价,我在一个名为 blog 的文件夹中有三个降价文件,我想按日期顺序列出它们。问题是我不确定我做了什么来搞砸我的阵列。

这是我的 routes.js 文件

exports.list = function(req, res){
  var walk = require('walk'), fs = require('fs'), options, walker;
  var walker = walk.walk('blog');
  var fs = new Array();
  walker.on("file", function(root,file,next){
    var f = root + "/" + file['name'].substring(0, file['name'].lastIndexOf('.'));
    // push without /blog prefix
    if (file['name'].substr(-2) == "md") {
        fs.push(f.substring(f.indexOf('/')));
        console.log(fs);

    }
    next();
  });
  walker.on("end", function() {
      var model = {
            layout:'home.hbs',
            title: 'Entries',
            files: fs
        };
    res.render('home.hbs', model)
  });
};

但我在终端返回的是:

[ '/first' ]
[ '/first', '/second' ]
[ '/first', '/second', '/third' ]

假设我只想显示前两个并让它们在降价文件中按日期排序,如下所示:

Title:  Lorem Ipsum dolor sit amet
Date:   January 2d, 2012

# test message

我的数组/其余代码有什么问题

4

1 回答 1

3

我注意到的第一件事是重新声明fs变量。第 2 行是 Node 的文件系统模块,第 4 行是(如果你问我new Array()应该是)。[]

我也不确定什么是walker模块,因为它的github repo被删除并且npm 包已经过时,我建议你使用原始文件系统模块API 来列出文件,可能是路径模块来处理你的文件位置和一些异步来粘合它一起:

// `npm install async` first.
// https://github.com/caolan/async
var fs    = require('fs');
var async = require('async');

// Lists directory entries in @dir,
// filters those which names ends with @extension.
// calls callback with (err, array of strings).
//
// FIXME:
// Mathes directories - solution is fs.stat()
// (could also sort here by mtime).
function listFiles(dir, extension, callback) {
  fs.readdir(dir, function(err, files) {
    if (err) {
      console.error('Failed to list files in `%s`: %s', dir, err);
      return callback(err);
    }

    var slicePos = -extension.length;
    callback(null, files.filter(function(filename) {
      return (extension == filename.slice(slicePos))
    }));
  });
}

// Sorts markdown based on date entry.
// Should be based on `mtime`, I think,
// since reading whole file isn't great idea.
// (See fs.Stats.)
// At lease add caching or something, you'll figure :)
//
// Also, you better get yourself a nice markdown parser,
// but for brevity I assume that first 2 lines are:
// Title:  Some Title
// Date:   Valid Javascript Datestring
function sortMarkdown(pathes, callback) {
  async.sortBy(pathes, function(fileName, cb) {
    // Following line is dirty!
    // You should probably pass absolute pathes here
    // to avoid errors. Path and Fs modules are your friends.
    var md = __dirname + '/blogs/' + fileName;

    fs.readFile(md, 'utf8', function(err, markdown) {
      if (err) {
        console.error('Failed to read `%s`: %s', md, err);
        return cb(err);
      }

      // Get second line of md.
      var date = markdown.split('\n')[1];

      // Get datestring with whitespaces removed.
      date = date.split(':')[1].trim();

      // Get timestamp. Change with -ts
      // to reverse sorting order.
      var ts = Date.parse(date);

      // Tell async how to sort; for details, see:
      // https://github.com/caolan/async#sortBy
      cb(null, ts);
    });
  }, callback);
}

function listSortedMarkdown(dir, callback) {
  // Async is just great!
  // https://github.com/caolan/async#waterfall
  async.waterfall([
    async.apply(listFiles, dir, '.md'),
    sortMarkdown,
  ], callback);
}

listSortedMarkdown(__dirname + '/blogs', function(err, sorted) {
  return err ? console.error('Error: %s', err)
             : console.dir(sorted);
});
于 2012-11-22T03:37:28.977 回答