Debian Codegraph @

deferred/examples/process-directory-of-html-files.js

raw
1 "use strict";
2
3 // Read meta data out of each html file in given directory.
4 // Requires jsdom package installed:
5 //
6 // $ npm install jsdom
7 //
8 // and folder with some html files
9 //
10 // Usage:
11 //
12 // var extract = require('deferred/examples/process-directory-of-html-files');
13 // extract('/some/path/to/html/files').done(function (result) {
14 // console.log("Result:", result);
15 // });
16
17 var fs = require("fs")
18 , path = require("path")
19 , jsdom = require("jsdom")
20 , deferred = require("deferred");
21
22 // Convert Node.js async functions, into ones that return a promise
23 var promisify = deferred.promisify
24 , readdir = promisify(fs.readdir)
25 , open = promisify(fs.open)
26 , read = promisify(fs.read)
27 , close = promisify(fs.close)
28 , stat = promisify(fs.stat)
29 , extract
30 , readFirstBytes;
31
32 extract = function (html) {
33 var def = deferred(), data = this;
34
35 // Process HTML with jsdom parser
36 jsdom.env({
37 html: String(html),
38 done: function (errors, window) {
39 var elems;
40 if (errors) {
41 def.reject(new Error(errors));
42 return;
43 }
44
45 // The title is the content of the 1st "h1" element
46 elems = window.document.getElementsByTagName("h1");
47 if (elems.length) data.title = elems[0].textContent;
48
49 // The description is the content of the 1st "p" element
50 elems = window.document.getElementsByTagName("p");
51 if (elems.length) data.description = elems[0].textContent;
52 def.resolve(data);
53 }
54 });
55
56 return def.promise;
57 };
58
59 readFirstBytes = function (filePath, byteCount) {
60 return open(filePath, "r").then(function (fd) {
61 var buffer = Buffer.alloc(byteCount);
62 return read(fd, buffer, 0, buffer.length, null).then(
63 // The callback of fs.read has 2 args: bytesRead, buffer
64 function (args) {
65 close(fd);
66 return String(args[1]);
67 }
68 );
69 });
70 };
71
72 module.exports = function (rootPath) {
73 var result = {};
74
75 // Read folder
76 //
77 // Note: If you are about to process large numbers of files, on some systems
78 // you may approach EMFILE error, which means that your process tried to open
79 // more file descriptors than it's allowed to. You can workaround it in two
80 // ways:
81 // 1. Load `descriptorsHandler` from fs2 package
82 // (see https://github.com/medikoo/fs2#descriptorshandler ),
83 // note it must not be loaded from generic package, but only at the top of
84 // your start program.
85 //
86 // 2. Limit initialization of concurrent asynchronous operations with
87 // `deferred.gate`:
88 //
89 // readdir(root).map(deferred.gate(function (fileName) { ... }, 100);
90 //
91 // Above will invoke no more than 100 concurrent async calls of `readFile`
92 // as they're called in function passed to `gate`
93
94 return readdir(rootPath).map(function (fileName) {
95 // Process only HTML files
96 if (path.extname(fileName) !== ".html") return null;
97
98 // Note: You may also use `readdir` from `fs2` package (needs to be
99 // installed aside), then you can configure `readdir` so it results only
100 // with expected set of filenames and additionally you can recurse into sub
101 // directories:
102 //
103 // var readdir = require('fs2/readdir');
104 //
105 // readdir(root, {
106 // depth: Infinity // Recurse into subdirectories
107 // type: { file: true } // Only files (no directories, symlinks etc)
108 // pattern: /.*\.html$/ // Only files with .html extension
109 // }).map(function (fileName) {
110 //
111 // `readdir` from fs2 returns promise by itself, so it doesn't have to be
112 // promisified
113
114 // Resolve full path to file
115 fileName = path.resolve(rootPath, fileName);
116
117 // Read file stats
118 return stat(fileName).then(function (stats) {
119 var data = { stats: stats, fileName: fileName };
120 result[fileName] = data;
121
122 // We read just first 12k bytes, but you can also parse whole HTML
123 // document with following:
124 //
125 // var readFile = promisify(fs.readFile);
126 // return readFile(fileName);
127
128 return readFirstBytes(fileName, 12000).then(extract.bind(data));
129 });
130 })(result);
131 };