forked from mooz/node-icu-charset-detector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node-icu-charset-detector.js
43 lines (34 loc) · 1.09 KB
/
node-icu-charset-detector.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var CharsetMatch = require("./build/Release/node-icu-charset-detector").CharsetMatch;
function detectCharset(buffer, options) {
var charsetMatch = new CharsetMatch(buffer);
if (charsetMatch.getName() === null) {
return null;
}
var charset = new String(charsetMatch.getName());
charset.language = charsetMatch.getLanguage();
charset.confidence = charsetMatch.getConfidence();
return charset;
}
function detectCharsetStream(stream, onDetectionFinish) {
var buffer = null;
var finished = false;
function onChunkArrives(chunk) {
buffer = buffer ? Buffer.concat(buffer, chunk) : chunk;
var charset = detectCharset(buffer);
if (charset !== null) {
// detection succeed. stop reading chunks.
stream.removeListener("data", onChunkArrives);
finished = true;
onDetectionFinish(charset);
}
}
stream.on("data", onChunkArrives);
stream.on("end", function () {
if (!finished) {
onDetectionFinish(null);
}
});
}
exports.detectCharset = detectCharset;
exports.detectCharsetStream = detectCharsetStream;
exports.CharsetMatch = CharsetMatch;