fetch-posts.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const fs = require('fs')
  2. const mdYmlParser = require('markdown-yaml-metadata-parser');
  3. var utilities = require('./utilities');
  4. const getDirectories = source =>
  5. fs.readdirSync(source, { withFileTypes: true })
  6. .filter(item => item.isDirectory())
  7. .map(item => item.name);
  8. const getFiles = source =>
  9. fs.readdirSync(source, { withFileTypes: true })
  10. .filter(item => !item.isDirectory())
  11. .map(item => item.name);
  12. var source = "/Users/james/codex/blog"
  13. var file_names = getFiles(source);
  14. var posts = []
  15. file_names.forEach(file_name => {
  16. if(file_name != '.DS_Store'){
  17. var file = fs.readFileSync(`${source}/${file_name}`, "utf8");
  18. var post = mdYmlParser(file);
  19. post.filename = file_name;
  20. if(post.metadata.published == true){
  21. posts.push(post);
  22. }
  23. }
  24. });
  25. console.log(`Found ${posts.length} posts. Creating files:`);
  26. var createPost = function(post){
  27. // Create folder
  28. var post_name = post.filename.split(".")[0];
  29. utilities.createDirectory(`source/_posts/blog/${post_name}`)
  30. // Copy post
  31. var post_path = `${source}/${post.filename}`
  32. var post_destination = `source/_posts/blog/${post_name}.md`;
  33. fs.copyFileSync(post_path, post_destination);
  34. // Copy hero image
  35. var hero_path = `${source}/images/${post.metadata.hero_image}`;
  36. var hero_destination = `source/_posts/blog/${post_name}/hero.jpg`
  37. fs.copyFileSync(hero_path, hero_destination);
  38. // Copy cover image
  39. var thumb_path = `${source}/images/${post.metadata.cover_image}`;
  40. var thumb_destination = `source/_posts/blog/${post_name}/cover.jpg`
  41. fs.copyFileSync(thumb_path, thumb_destination);
  42. }
  43. var counter = 0;
  44. posts.forEach(post => {
  45. try{
  46. createPost(post);
  47. counter += 1;
  48. } catch(err){
  49. console.log(err);
  50. }
  51. });
  52. //console.log(`Created ${counter} blog posts`);