savePost.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. SavePost.js
  3. This script save the post to the given location
  4. Require paramters:
  5. - filepath
  6. - title
  7. - tags
  8. - content (HTML, not markdown)
  9. - webroot (Web deploy root)
  10. */
  11. //Require libraries
  12. includes("config.js")
  13. includes("helper.js")
  14. function main(){
  15. //Get a safe title from removing all special characters
  16. var safeTitle = title.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
  17. var postObjectName = Date.now() + "-" + safeTitle;
  18. var saveFilename = getBlogPostStore() + "posts/" + postObjectName + ".json"
  19. if (filepath == "" || !filelib.fileExists(filepath)){
  20. //This is a new file or the original file not exists. Assign a filename for it
  21. filepath = saveFilename;
  22. }else{
  23. //Extract the post object name from the path
  24. var tmp = filepath.split("/").pop();
  25. var fname = tmp.split(".");
  26. fname.pop();
  27. postObjectName = fname.join(".");
  28. console.log(postObjectName);
  29. }
  30. //Generate tags array
  31. var tagArray = [];
  32. tags = tags.split(",");
  33. for(var i = 0; i < tags.length; i++){
  34. var thisTag = tags[i].trim();
  35. if (thisTag != ""){
  36. tagArray.push(thisTag);
  37. }
  38. }
  39. //Generate the blog post storage object
  40. var blogObject = {
  41. Title: title,
  42. Tags: tagArray,
  43. Content: content,
  44. }
  45. //Write to file
  46. var postObjectEncoded = JSON.stringify(blogObject);
  47. filelib.writeFile(filepath, postObjectEncoded);
  48. //Check if this is published. IF yes, update the render as well
  49. var publishWebPosition = filepathClean(webroot) + "/blog/posts/" + postObjectName + ".html";
  50. if (filelib.fileExists(publishWebPosition)){
  51. includes("publish.js");
  52. var runAsFunc = true;
  53. publish(filepath, webroot)
  54. }
  55. //Send back the filepath for save confirmation
  56. sendResp(filepath);
  57. }
  58. main();