stringify.js 1.4 KB

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