You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

117 lines
2.8 KiB

  1. fs = require('fs')
  2. function md_trim(str) {
  3. str = str.replace(/(^\s+)|(\s+$)/g, "");
  4. if (str.lastIndexOf("[Go!]", 0) === 0) {
  5. str = str.replace("[Go!]", "").slice(1, -1);
  6. }
  7. return str;
  8. }
  9. function handle(filename, anchor) {
  10. fs.readFile(filename, 'utf8', function (err,text) {
  11. if (err) {
  12. return console.log(err);
  13. }
  14. var lines = text.split("\n");
  15. var cur_line = 0;
  16. var line = ""
  17. var table_name = "";
  18. var col_num = 0;
  19. var cols = [];
  20. var rows = [];
  21. function read_line() {
  22. return lines[cur_line++];
  23. }
  24. var root = {};
  25. while (true) {
  26. var cols = [];
  27. var rows = [];
  28. while (line.indexOf(anchor) == -1 && cur_line != lines.length) {
  29. line = read_line();
  30. }
  31. if (cur_line == lines.length) {
  32. break;
  33. }
  34. table_name = line.split(anchor)[1];
  35. table_name = md_trim(table_name)
  36. line = read_line()
  37. if (line) {
  38. line = line.split("|")
  39. for (var j in line) {
  40. line[j] = md_trim(line[j])
  41. if ((j == 0 || j == line.length - 1) && line[j] === "") {
  42. } else {
  43. cols.push(line[j]);
  44. }
  45. }
  46. if (line.length) {
  47. cols = line;
  48. rows.push(cols)
  49. } else {
  50. console.error("markdown expect column title")
  51. break;
  52. }
  53. } else {
  54. console.error("markdown expect table content")
  55. break;
  56. }
  57. line = read_line()
  58. if (line) {
  59. } else {
  60. console.error("markdown expect table spliter")
  61. break;
  62. }
  63. line = read_line()
  64. while (line.indexOf("|") != -1 && cur_line != lines.length) {
  65. var line_this = line.split("|")
  66. var row = []
  67. for (var j in line_this) {
  68. line_this[j] = md_trim(line_this[j])
  69. if ((j == 0 || j == line_this.length - 1) && line_this[j] === "") {
  70. } else {
  71. row.push(line_this[j]);
  72. }
  73. }
  74. rows.push(row);
  75. line = read_line()
  76. }
  77. var data=[];
  78. for (var j in rows) {
  79. if (j != 0) {
  80. var ele = {};
  81. for (var k in rows[j]) {
  82. ele[rows[0][k]] = rows[j][k];
  83. }
  84. data.push(ele);
  85. }
  86. }
  87. root[table_name] = data;
  88. }
  89. console.log(JSON.stringify(root));
  90. });
  91. }
  92. if (process.argv.length < 3) {
  93. console.log("No .md file passed!");
  94. return;
  95. }
  96. if (process.argv.length < 4) {
  97. anchorText = "###";
  98. } else {
  99. anchorText = process.argv[3];
  100. }
  101. handle(process.argv[2].toString(), anchorText);