single-file 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. #!/usr/bin/env node
  2. /*
  3. * Copyright 2010-2020 Gildas Lormeau
  4. * contact : gildas.lormeau <at> gmail.com
  5. *
  6. * This file is part of SingleFile.
  7. *
  8. * The code in this file is free software: you can redistribute it and/or
  9. * modify it under the terms of the GNU Affero General Public License
  10. * (GNU AGPL) as published by the Free Software Foundation, either version 3
  11. * of the License, or (at your option) any later version.
  12. *
  13. * The code in this file is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  16. * General Public License for more details.
  17. *
  18. * As additional permission under GNU AGPL version 3 section 7, you may
  19. * distribute UNMODIFIED VERSIONS OF THIS file without the copy of the GNU
  20. * AGPL normally required by section 4, provided you include this license
  21. * notice and a URL through which recipients can access the Corresponding
  22. * Source.
  23. */
  24. /* global require */
  25. const fileUrl = require("file-url");
  26. const args = require("yargs")
  27. .wrap(null)
  28. .command("$0 [url] [output]", "Save a page into a single HTML file.", yargs => {
  29. yargs.positional("url", { description: "URL or path on the filesystem of the page to save", type: "string" });
  30. yargs.positional("output", { description: "Output filename", type: "string" });
  31. })
  32. .default({
  33. "back-end": "puppeteer",
  34. "browser-headless": true,
  35. "browser-executable-path": "",
  36. "browser-width": 1280,
  37. "browser-height": 720,
  38. "browser-load-max-time": 60000,
  39. "browser-wait-until": "networkidle0",
  40. "browser-debug": false,
  41. "browser-extensions": [],
  42. "browser-scripts": [],
  43. "browser-args": "",
  44. "compress-CSS": false,
  45. "compress-HTML": true,
  46. "filename-template": "{page-title} ({date-iso} {time-locale}).html",
  47. "filename-replacement-character": "_",
  48. "group-duplicate-images": true,
  49. "include-infobar": false,
  50. "load-deferred-images": true,
  51. "load-deferred-images-max-idle-time": 1500,
  52. "maxParallelWorkers": 8,
  53. "max-resource-size-enabled": false,
  54. "max-resource-size": 10,
  55. "remove-hidden-elements": true,
  56. "remove-unused-styles": true,
  57. "remove-unused-fonts": true,
  58. "remove-frames": false,
  59. "remove-imports": true,
  60. "remove-scripts": true,
  61. "remove-audio-src": true,
  62. "remove-video-src": true,
  63. "remove-alternative-fonts": true,
  64. "remove-alternative-medias": true,
  65. "remove-alternative-images": true,
  66. "save-raw-page": false,
  67. "web-driver-executable-path": "",
  68. "user-script-enabled": true
  69. })
  70. .options("back-end", { description: "Back-end to use" })
  71. .choices("back-end", ["jsdom", "puppeteer", "webdriver-chromium", "webdriver-gecko", "puppeteer-firefox"])
  72. .options("browser-headless", { description: "Run the browser in headless mode (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  73. .boolean("browser-headless")
  74. .options("browser-executable-path", { description: "Path to chrome/chromium executable (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  75. .string("browser-executable-path")
  76. .options("browser-width", { description: "Width of the browser viewport in pixels" })
  77. .number("browser-width")
  78. .options("browser-height", { description: "Height of the browser viewport in pixels" })
  79. .number("browser-height")
  80. .options("browser-load-max-time", { description: "Maximum delay of time to wait for page loading in ms (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  81. .number("browser-load-max-time")
  82. .options("browser-wait-until", { description: "When to consider the page is loaded (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  83. .choices("browser-wait-until", ["networkidle0", "networkidle2", "load", "domcontentloaded"])
  84. .options("browser-debug", { description: "Enable debug mode (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  85. .boolean("browser-debug")
  86. .options("browser-extensions", { description: "List of extension paths separated by a space and relative to the 'cli' folder (webdriver-gecko, webdriver-chromium)" })
  87. .array("browser-extensions")
  88. .options("browser-scripts", { description: "List of script paths separated by a space and relative to the 'cli' folder. They will be executed in all the frames." })
  89. .array("browser-scripts")
  90. .options("browser-args", { description: "Arguments provided as a JSON array and passed to the browser (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  91. .string("browser-args")
  92. .options("compress-CSS", { description: "Compress CSS stylesheets" })
  93. .boolean("compress-CSS")
  94. .options("compress-HTML", { description: "Compress HTML content" })
  95. .boolean("compress-HTML")
  96. .options("error-file")
  97. .string("error-file")
  98. .options("filename-template", { description: "Template used to generate the output filename (see help page of the extension for more info)" })
  99. .string("filename-template")
  100. .options("filename-replacement-character", { description: "The character used for replacing invalid characters in filenames" })
  101. .string("filename-replacement-character")
  102. .string("filename-template")
  103. .options("group-duplicate-images", { description: "Group duplicate images into CSS custom properties" })
  104. .boolean("group-duplicate-images")
  105. .options("include-infobar", { description: "Include the infobar" })
  106. .boolean("include-infobar")
  107. .options("load-deferred-images", { description: "Load deferred (a.k.a. lazy-loaded) images (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  108. .boolean("load-deferred-images")
  109. .options("load-deferred-images-max-idle-time", { description: "Maximum delay of time to wait for deferred images in ms (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  110. .number("load-deferred-images-max-idle-time")
  111. .options("max-parallel-workers", { description: "Maximum number of browsers launched in parallel when processing a list of URLs (cf --urls-file)" })
  112. .number("max-parallel-workers")
  113. .options("max-resource-size-enabled", { description: "Enable removal of embedded resources exceeding a given size" })
  114. .boolean("max-resource-size-enabled")
  115. .options("max-resource-size", { description: "Maximum size of embedded resources in MB (i.e. images, stylesheets, scripts and iframes)" })
  116. .number("max-resource-size")
  117. .options("remove-frames", { description: "Remove frames (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  118. .boolean("remove-frames")
  119. .options("remove-hidden-elements", { description: "Remove HTML elements which are not displayed" })
  120. .boolean("remove-hidden-elements")
  121. .options("remove-unused-styles", { description: "Remove unused CSS rules and unneeded declarations" })
  122. .boolean("remove-unused-styles")
  123. .options("remove-unused-fonts", { description: "Remove unused CSS font rules" })
  124. .boolean("remove-unused-fonts")
  125. .options("remove-imports", { description: "Remove HTML imports" })
  126. .boolean("remove-imports")
  127. .options("remove-scripts", { description: "Remove JavaScript scripts" })
  128. .boolean("remove-scripts")
  129. .options("remove-audio-src", { description: "Remove source of audio elements" })
  130. .boolean("remove-audio-src")
  131. .options("remove-video-src", { description: "Remove source of video elements" })
  132. .boolean("remove-video-src")
  133. .options("remove-alternative-fonts", { description: "Remove alternative fonts to the ones displayed" })
  134. .boolean("remove-alternative-fonts")
  135. .options("remove-alternative-medias", { description: "Remove alternative CSS stylesheets" })
  136. .boolean("remove-alternative-medias")
  137. .options("remove-alternative-images", { description: "Remove images for alternative sizes of screen" })
  138. .boolean("remove-alternative-images")
  139. .options("save-raw-page", { description: "Save the original page without interpreting it into the browser (puppeteer, puppeteer-firefox, webdriver-gecko, webdriver-chromium)" })
  140. .boolean("save-raw-page")
  141. .options("urls-file", { description: "Path to a text file containing a list of URLs (separated by a newline) to save" })
  142. .string("urls-file")
  143. .options("user-agent", { description: "User-agent of the browser (puppeteer, webdriver-gecko, webdriver-chromium)" })
  144. .string("user-agent")
  145. .options("user-script-enabled", { description: "Enable the event API allowing to execute scripts before the page is saved" })
  146. .boolean("user-script-enabled")
  147. .options("web-driver-executable-path", { description: "Path to Selenium WebDriver executable (webdriver-gecko, webdriver-chromium)" })
  148. .string("web-driver-executable-path")
  149. .argv;
  150. const fs = require("fs");
  151. const backEnds = {
  152. jsdom: "./back-ends/jsdom.js",
  153. puppeteer: "./back-ends/puppeteer.js",
  154. "puppeteer-firefox": "./back-ends/puppeteer-firefox.js",
  155. "webdriver-chromium": "./back-ends/webdriver-chromium.js",
  156. "webdriver-gecko": "./back-ends/webdriver-gecko.js"
  157. };
  158. args.compressCSS = args.compressCss;
  159. args.compressHTML = args.compressHtml;
  160. if (args.url && !/^(https?|file):\/\//.test(args.url)) {
  161. args.url = fileUrl(args.url);
  162. }
  163. args.browserScripts = args.browserScripts.map(path => require.resolve(path));
  164. const backend = require(backEnds[args.backEnd]);
  165. backend.initialize(args).then(() => {
  166. if (args.urlsFile) {
  167. const urls = fs.readFileSync(args.urlsFile).toString().split("\n").map(url => url.trim()).filter(url => url);
  168. for (let workerIndex = 0; workerIndex < args.maxParallelWorkers; workerIndex++) {
  169. workerCapturePage(args, urls, workerIndex);
  170. }
  171. } else {
  172. capturePage(args);
  173. }
  174. });
  175. async function workerCapturePage(args, urls, workerIndex, depth = 0) {
  176. const url = urls[workerIndex + (depth * args.maxParallelWorkers)];
  177. if (url) {
  178. args = JSON.parse(JSON.stringify(args));
  179. args.url = url;
  180. args.output = null;
  181. await capturePage(args);
  182. await workerCapturePage(args, urls, workerIndex, depth + 1);
  183. }
  184. }
  185. async function capturePage(args) {
  186. try {
  187. const pageData = await backend.getPageData(args);
  188. if (args.output) {
  189. fs.writeFileSync(getFilename(args.output), pageData.content);
  190. } else {
  191. if (args.filenameTemplate && pageData.filename) {
  192. fs.writeFileSync(getFilename(pageData.filename), pageData.content);
  193. } else {
  194. console.log(pageData.content); // eslint-disable-line no-console
  195. }
  196. }
  197. } catch (error) {
  198. const message = "URL: " + args.url + "\nStack: " + error.stack + "\n";
  199. if (args.errorFile) {
  200. fs.writeFileSync(args.errorFile, message, { flag: "a" });
  201. } else {
  202. console.error(message);// eslint-disable-line no-console
  203. }
  204. }
  205. }
  206. function getFilename(filename, index = 1) {
  207. let newFilename = filename;
  208. if (index > 1) {
  209. const regExpMatchExtension = /(\.[^.]+)$/;
  210. const matchExtension = newFilename.match(regExpMatchExtension);
  211. if (matchExtension && matchExtension[1]) {
  212. newFilename = newFilename.replace(regExpMatchExtension, " - " + index + matchExtension[1]);
  213. } else {
  214. newFilename += " - " + index;
  215. }
  216. }
  217. if (fs.existsSync(newFilename)) {
  218. return getFilename(filename, index + 1);
  219. } else {
  220. return newFilename;
  221. }
  222. }