fetch-posts.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const fs = require('fs')
  2. const mdYmlParser = require('markdown-yaml-metadata-parser');
  3. const getDirectories = source =>
  4. fs.readdirSync(source, { withFileTypes: true })
  5. .filter(item => item.isDirectory())
  6. .map(item => item.name);
  7. const getFiles = source =>
  8. fs.readdirSync(source, { withFileTypes: true })
  9. .filter(item => !item.isDirectory())
  10. .map(item => item.name);
  11. var source = "/Users/james/codex/blog"
  12. var file_names = getFiles(source);
  13. var posts = []
  14. file_names.forEach(file_name => {
  15. if(file_name != '.DS_Store'){
  16. var file = fs.readFileSync(`${source}/${file_name}`, "utf8");
  17. var post = mdYmlParser(file);
  18. post.filename = file_name;
  19. if(post.metadata.draft == false){
  20. posts.push(post);
  21. }
  22. }
  23. });
  24. console.log(`Found ${posts.length} posts. Creating files:`);
  25. var createPost = function(post){
  26. // Copy post
  27. var post_path = `${source}/${post.filename}`
  28. var post_name = post.filename.split(".")[0];
  29. var post_destination = `source/_posts/blog/${post_name}.md`;
  30. fs.copyFileSync(post_path, post_destination);
  31. console.log(`- \'${post.filename}\'`);
  32. // Copy hero image
  33. var hero_path = `${source}/images/hero/${post.metadata.image.feature}`;
  34. var hero_destination = `source/images/hero/blog/${post.metadata.image.feature}`
  35. fs.copyFileSync(hero_path, hero_destination);
  36. console.log(`- \'hero/${post.metadata.image.feature}\'`);
  37. // Copy thumbnail image
  38. var thumb_path = `${source}/images/thumbnails/${post.metadata.image.feature}`;
  39. var thumb_destination = `source/images/thumbnails/blog/${post.metadata.image.feature}`
  40. fs.copyFileSync(thumb_path, thumb_destination);
  41. console.log(`- \'thumbnails/${post.metadata.image.feature}\'`);
  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`);