2012-11-21 54 views
0

因此,我决定重做一个博客并使用降价,我在一个名为blog的文件夹中有三个降价文件,并且希望按日期排列它们。问题是我不知道我做了什么来搞砸我的阵列。列出降价文件

我的继承人routes.js文件

​​3210

但我返回终端是这样的:

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

说我只是想显示前两并将它们按日期排序的markdown文件,如下所示:

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

# test message 

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

回答

3

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

我也不知道什么是walker模块,因为它是github repo取出并npm package是过时的,我推荐你使用原始filesystem module API列出文件,可能path module来处理你的文件的位置和一些async胶水它在一起:

// `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); 
}); 
+0

谢谢你,我在找什么。 – lostAstronaut