UNPKG

1.55 kBJavaScriptView Raw
1var basename = require('path').basename;
2var debug = require('debug')('metalsmith-markdown');
3var dirname = require('path').dirname;
4var extname = require('path').extname;
5var join = require('path').join;
6var marked = require('marked');
7
8/**
9 * Check if a `file` is markdown.
10 *
11 * @param {String} file
12 * @return {Boolean}
13 */
14var markdown = function(file) {
15 return /\.md$|\.markdown$/.test(extname(file));
16};
17
18/**
19 * Metalsmith plugin to convert markdown files.
20 *
21 * @param {Object} options (optional)
22 * @property {Array} keys
23 * @return {Function}
24 */
25var plugin = function(options) {
26 options = options || {};
27 var keys = options.keys || [];
28
29 return function(files, metalsmith, done) {
30 setImmediate(done);
31 Object.keys(files).forEach(function(file) {
32 debug('checking file: %s', file);
33 if (!markdown(file)) return;
34 var data = files[file];
35 var dir = dirname(file);
36 var html = basename(file, extname(file)) + '.html';
37 if ('.' != dir) html = join(dir, html);
38
39 debug('converting file: %s', file);
40 var str = marked(data.contents.toString(), options);
41 try {
42 // preferred
43 data.contents = Buffer.from(str);
44 } catch (err) {
45 // node versions < (5.10 | 6)
46 data.contents = new Buffer(str);
47 }
48 keys.forEach(function(key) {
49 if (data[key]) {
50 data[key] = marked(data[key].toString(), options);
51 }
52 });
53
54 delete files[file];
55 files[html] = data;
56 });
57 };
58};
59
60// Expose Plugin
61module.exports = plugin;