epub2md 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,18 @@
2
2
 
3
3
  Even though the package is primarily intended for CLI is to convert EPUB to Markdown, but it can be used programmatically.
4
4
 
5
- 主要的目标是转换 epub markdown,当然了也可以当做 epub 的解析器库使用.
5
+ 主要的目标是转换 epub 多个 markdown 文件,或者合并为 单个 markdown 文件,可以处理其中的远程图片资源;当然了也可以当做 epub 的解析器库使用.
6
+
7
+ ## Main Functions
8
+
9
+ - **Convert EPUB to Markdown**: By default, convert and output numbered markdown files in sequence.
10
+ - **Autocorrection**: Have option to Handle spaces and punctuation between Chinese and English as You Need.
11
+ - **Merge Chapters**: Optionally merge all markdown files into a single Markdown file, Support link jumping.
12
+ - **Image Processing**:
13
+ - Retain the original online image links.
14
+ - Download and localize online images (save remote images locally).
15
+ - **View Information**: Easy to View the basic information, structure, and chapters of the EPUB.
16
+ - **Extraction Function**: Dont need convert, just extract the useful contents of the EPUB file.
6
17
 
7
18
  ## Global Install for CLI
8
19
 
@@ -27,22 +38,51 @@ $ npm install @uxiew/epub2md
27
38
  ## CLI
28
39
 
29
40
  ```bash
30
- # show usage
41
+ # Show usage help
31
42
  $ epub2md -h
32
43
 
33
44
  # Convert directly to markdown format
34
45
  $ epub2md ../../fixtures/zhihu.epub
35
- # or -m
46
+ # or use -m
36
47
  $ epub2md -m ../../fixtures/zhihu.epub
37
48
 
38
- # Convert directly to markdown format with autocorrect to handle spacing between CJK and English words and Correct punctuations Only for command line use
49
+ # Convert multiple files using wildcards
50
+ $ epub2md "fixtures/*.epub"
51
+ $ epub2md "books/fiction-*.epub"
52
+ $ epub2md "library/file-[123].epub"
53
+
54
+ # Convert multiple files with merge (each file gets its own merged output)
55
+ $ epub2md "fixtures/*.epub" --merge
56
+
57
+ # Note: Quotes are required around patterns with wildcards to prevent shell expansion
58
+
59
+ # Convert to markdown and automatically correct spaces and punctuation between Chinese and English (CLI only)
39
60
  $ epub2md -M ../../fixtures/zhihu.epub
40
61
 
41
- # show other info
42
- $ epub2md -u ../../fixtures/zhihu.epub
43
- $ epub2md -i ../../fixtures/zhihu.epub
44
- $ epub2md -S ../../fixtures/zhihu.epub
45
- $ epub2md -s ../../fixtures/zhihu.epub
62
+ # Convert and directly generate a single merged markdown file (no intermediate files)
63
+ $ epub2md -m ../../fixtures/zhihu.epub --merge
64
+ # You can also use the epub file path as the first parameter directly
65
+ $ epub2md ../../fixtures/zhihu.epub --merge
66
+
67
+ # Use --merge=filename.md
68
+ $ epub2md ../../fixtures/zhihu.epub --merge="merged-book.md"
69
+
70
+ # By default, DONT downloaded. Basically, the images in the epub are already included, so there is no need to download.
71
+ # However, some epub image links are remote, You will see some warning,maybe they need to be downloaded.
72
+ # Download and localize online images (download remote images to local) (need node > 18.0)
73
+ $ epub2md ../../fixtures/zhihu.epub --localize
74
+
75
+ # Download and localize online images, while merging all chapters into a single file
76
+ $ epub2md ../../fixtures/zhihu.epub --merge --localize
77
+
78
+ # Merge existing markdown files in a directory
79
+ $ epub2md --merge ./path/to/markdown/dir
80
+
81
+ # Show additional information
82
+ $ epub2md -u ../../fixtures/zhihu.epub # Extract epub
83
+ $ epub2md -i ../../fixtures/zhihu.epub # Show basic information
84
+ $ epub2md -S ../../fixtures/zhihu.epub # Show structure information
85
+ $ epub2md -s ../../fixtures/zhihu.epub # Show chapter information
46
86
  ```
47
87
 
48
88
  ## Usage
package/lib/bin/cli.cjs CHANGED
@@ -6,59 +6,160 @@ Object.defineProperty(exports, "__esModule", {
6
6
  });
7
7
  exports.Commands = void 0;
8
8
  var _args = _interopRequireDefault(require("args"));
9
- var _chalk = _interopRequireDefault(require("chalk"));
10
9
  var _nodeProcess = _interopRequireDefault(require("node:process"));
10
+ var _nodeFs = _interopRequireDefault(require("node:fs"));
11
11
  var _parseEpub = _interopRequireDefault(require("../parseEpub.cjs"));
12
12
  var _convert = require("./convert.cjs");
13
- var _beautyJson = require("beauty-json");
13
+ var _merge = require("./merge.cjs");
14
+ var _logger = _interopRequireDefault(require("../logger.cjs"));
15
+ var _utils = require("./utils.cjs");
14
16
  function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
15
17
  const name = "epub2md";
16
- var Commands = exports.Commands = /* @__PURE__ */(Commands2 => {
17
- Commands2["markdown"] = "md";
18
- Commands2["autocorrect"] = "ma";
19
- Commands2["unzip"] = "unzip";
20
- Commands2["info"] = "info";
21
- Commands2["structure"] = "structure";
22
- Commands2["sections"] = "sections";
23
- return Commands2;
24
- })(Commands || {});
25
- const commands = [["md" /* markdown */, "convert the epub file to markdown format"], ["ma" /* autocorrect */, "convert the epub file to markdown format with autocorrect"], ["unzip" /* unzip */, "unzip epub file"], ["info" /* info */, "get epub file basic info"], ["structure" /* structure */, "get epub file structure"], ["sections" /* sections */, "get epub file sections"]];
26
- const DEFAULT_COMMAND = "md" /* markdown */;
27
- commands.forEach(cmd => _args.default.option(cmd[0], cmd[1]));
18
+ const Commands = exports.Commands = {
19
+ convert: "convert",
20
+ autocorrect: "autocorrect",
21
+ unzip: "unzip",
22
+ info: "info",
23
+ structure: "structure",
24
+ sections: "sections",
25
+ merge: "merge",
26
+ localize: "localize"
27
+ };
28
+ const commands = [[Commands.convert, "convert the epub file to markdown format"], [Commands.autocorrect, "convert the epub file to markdown format with autocorrect"], [Commands.unzip, "unzip epub file"], [Commands.info, "get epub file basic info"], [Commands.structure, "get epub file structure"], [Commands.sections, "get epub file sections"], [Commands.merge, "merge all markdown files into a single file, can also specify output filename with --merge=filename.md"], [Commands.localize, "Retain the original online link and do not convert it to a local path", false]];
29
+ const DEFAULT_COMMAND = Commands.convert;
30
+ commands.forEach(cmd => _args.default.option(cmd[0], cmd[1], cmd[2]));
28
31
  const flags = _args.default.parse(_nodeProcess.default.argv, {
29
32
  name
30
33
  });
31
- commands.some(([cmd], i) => {
34
+ const unprocessedArgs = _nodeProcess.default.argv.slice(2).filter(arg => !arg.startsWith("--") && !arg.startsWith("-"));
35
+ if (unprocessedArgs.length > 0) {
36
+ flags[DEFAULT_COMMAND] = unprocessedArgs[0];
37
+ }
38
+ let hasRun = false;
39
+ for (const cmd of [Commands.info, Commands.structure, Commands.sections]) {
32
40
  if (flags[cmd]) {
33
- run(cmd);
34
- return true;
35
- } else {
36
- if (i === commands.length - 1) {
37
- if (_nodeProcess.default.argv[2]) {
38
- flags[DEFAULT_COMMAND] = _nodeProcess.default.argv[2];
39
- run(DEFAULT_COMMAND);
40
- return true;
41
+ if (typeof flags[cmd] !== "string") {
42
+ if (unprocessedArgs.length > 0) {
43
+ flags[cmd] = unprocessedArgs[0];
41
44
  }
42
- _args.default.showHelp();
45
+ }
46
+ if (typeof flags[cmd] === "string") {
47
+ run(cmd);
48
+ hasRun = true;
49
+ break;
43
50
  }
44
51
  }
45
- });
46
- function run(cmd) {
47
- const epubPath = flags["md" /* markdown */] || flags["ma" /* autocorrect */] || flags["unzip" /* unzip */];
52
+ }
53
+ if (!hasRun && flags[Commands.unzip]) {
54
+ const epubPath = typeof flags[Commands.unzip] === "string" ? flags[Commands.unzip] : unprocessedArgs.length > 0 ? unprocessedArgs[0] : null;
48
55
  if (epubPath) {
49
- console.log(_chalk.default.blueBright(`[${name}]: converting${cmd === "ma" /* autocorrect */ ? " with AutoCorrect" : ""}...`));
50
- new _convert.Converter({
51
- eubPath: epubPath,
52
- cmd
53
- }).run(flags["unzip" /* unzip */]).then(outDir => {
54
- console.log(_chalk.default.greenBright(`[${name}]: success! output: ${outDir}`));
56
+ _logger.default.info("unzipping...");
57
+ new _convert.Converter(epubPath).run({
58
+ cmd: Commands.unzip,
59
+ // Use cmd to indicate unzip only
60
+ mergedFilename: void 0,
61
+ shouldMerge: false,
62
+ localize: false
63
+ }).then(outDir => {
64
+ _logger.default.info(`Unzip successful! output: ${outDir}`);
65
+ }).catch(error => {
66
+ _logger.default.error(error);
55
67
  });
68
+ hasRun = true;
69
+ } else {
70
+ _logger.default.error("No valid epub file path provided for unzip command");
71
+ }
72
+ }
73
+ if (!hasRun) {
74
+ if (flags.merge && typeof flags.merge === "string" && flags.merge !== "") {
75
+ if (_nodeFs.default.existsSync(flags.merge) && _nodeFs.default.statSync(flags.merge).isDirectory()) {
76
+ _logger.default.info("merging markdown files in directory...");
77
+ (0, _merge.mergeMarkdowns)(flags.merge).then(outputPath => {
78
+ _logger.default.info(`Merging successful! Output file: ${outputPath}`);
79
+ }).catch(error => {
80
+ _logger.default.info(`Merging failed: ${error}`);
81
+ });
82
+ hasRun = true;
83
+ }
84
+ }
85
+ if (!hasRun) {
86
+ for (const cmd of [Commands.convert, Commands.autocorrect]) {
87
+ if (flags[cmd]) {
88
+ if (typeof flags[cmd] !== "string") {
89
+ if (unprocessedArgs.length > 0) {
90
+ flags[cmd] = unprocessedArgs[0];
91
+ }
92
+ }
93
+ run(cmd);
94
+ hasRun = true;
95
+ break;
96
+ }
97
+ }
98
+ if (!hasRun && unprocessedArgs.length > 0) {
99
+ run(DEFAULT_COMMAND);
100
+ } else if (!hasRun) {
101
+ _args.default.showHelp();
102
+ }
103
+ }
104
+ }
105
+ async function run(cmd) {
106
+ if (cmd === Commands.convert || cmd === Commands.autocorrect) {
107
+ const epubPath = typeof flags[cmd] === "string" ? flags[cmd] : null;
108
+ if (!epubPath) {
109
+ _logger.default.error("No valid epub file path provided");
110
+ return;
111
+ }
112
+ const epubFiles = await (0, _utils.expandWildcard)(epubPath);
113
+ if (epubFiles.length === 0) {
114
+ _logger.default.error(`No files found matching pattern: ${epubPath}`);
115
+ return;
116
+ }
117
+ const shouldMerge = flags.merge === true || typeof flags.merge === "string" && flags.merge !== "";
118
+ let mergedFilename;
119
+ if (typeof flags.merge === "string" && flags.merge !== "") {
120
+ mergedFilename = flags.merge;
121
+ }
122
+ if (mergedFilename && epubFiles.length > 1) {
123
+ _logger.default.warn(`Warning: Using custom merge filename "${mergedFilename}" with multiple files. Each file will overwrite the previous merged output.`);
124
+ _logger.default.warn(`Consider using --merge (without filename) to generate separate merged files for each epub.`);
125
+ }
126
+ const localize = flags.localize === true;
127
+ if (epubFiles.length > 1) {
128
+ _logger.default.info(`Found ${epubFiles.length} files matching pattern "${epubPath}"`);
129
+ }
130
+ for (let i = 0; i < epubFiles.length; i++) {
131
+ const currentFile = epubFiles[i];
132
+ _logger.default.info(`[${i + 1}/${epubFiles.length}] Converting ${currentFile}${cmd === Commands.autocorrect ? " with autocorrect" : ""}${flags[Commands.merge] ? " and merging" : ""}...`);
133
+ try {
134
+ const outDir = await new _convert.Converter(currentFile).run({
135
+ cmd,
136
+ mergedFilename,
137
+ shouldMerge,
138
+ localize
139
+ });
140
+ if (shouldMerge) {
141
+ _logger.default.info(`[${i + 1}/${epubFiles.length}] Merging successful! Output file: ${outDir}`);
142
+ } else {
143
+ _logger.default.info(`[${i + 1}/${epubFiles.length}] Conversion successful! output: ${outDir}`);
144
+ }
145
+ } catch (error) {
146
+ _logger.default.error(`[${i + 1}/${epubFiles.length}] Failed to convert ${currentFile}:`, error);
147
+ }
148
+ }
149
+ if (epubFiles.length > 1) {
150
+ _logger.default.success(`Completed processing ${epubFiles.length} files`);
151
+ }
56
152
  return;
57
153
  }
58
- (0, _parseEpub.default)(flags[cmd]).then(res => {
59
- console.log(_chalk.default.greenBright(`[${name}]: This book ${cmd}:`));
60
- _beautyJson.json.log(res[cmd]);
61
- }).catch(error => {
62
- console.log(_chalk.default.red(error));
63
- });
154
+ const cmdPath = flags[cmd];
155
+ if (typeof cmdPath === "string") {
156
+ (0, _parseEpub.default)(cmdPath).then(res => {
157
+ _logger.default.success(`This book ${cmd}:`);
158
+ _logger.default.json(res[cmd]);
159
+ }).catch(error => {
160
+ _logger.default.error(error);
161
+ });
162
+ } else {
163
+ _logger.default.error(`Path must be a string, got ${typeof cmdPath}`);
164
+ }
64
165
  }