stringify.js (1427B)
1 'use strict'; 2 3 const typeOf = require('kind-of'); 4 const getEngine = require('./engine'); 5 const defaults = require('./defaults'); 6 7 module.exports = function(file, data, options) { 8 if (data == null && options == null) { 9 switch (typeOf(file)) { 10 case 'object': 11 data = file.data; 12 options = {}; 13 break; 14 case 'string': 15 return file; 16 default: { 17 throw new TypeError('expected file to be a string or object'); 18 } 19 } 20 } 21 22 const str = file.content; 23 const opts = defaults(options); 24 if (data == null) { 25 if (!opts.data) return file; 26 data = opts.data; 27 } 28 29 const language = file.language || opts.language; 30 const engine = getEngine(language, opts); 31 if (typeof engine.stringify !== 'function') { 32 throw new TypeError('expected "' + language + '.stringify" to be a function'); 33 } 34 35 data = Object.assign({}, file.data, data); 36 const open = opts.delimiters[0]; 37 const close = opts.delimiters[1]; 38 const matter = engine.stringify(data, options).trim(); 39 let buf = ''; 40 41 if (matter !== '{}') { 42 buf = newline(open) + newline(matter) + newline(close); 43 } 44 45 if (typeof file.excerpt === 'string' && file.excerpt !== '') { 46 if (str.indexOf(file.excerpt.trim()) === -1) { 47 buf += newline(file.excerpt) + newline(close); 48 } 49 } 50 51 return buf + newline(str); 52 }; 53 54 function newline(str) { 55 return str.slice(-1) !== '\n' ? str + '\n' : str; 56 }