forked from spamscanner/spamscanner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmbox-split.js
81 lines (71 loc) · 2.33 KB
/
mbox-split.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
const fs = require('fs');
const os = require('os');
const path = require('path');
const { promisify } = require('util');
const Mbox = require('node-mbox');
const makeDir = require('make-dir');
const pMap = require('p-map');
const trim = require('trim-leading-whitespace');
const { readDirDeep } = require('read-dir-deep');
const MBOX_PATTERNS = require('./mbox-patterns');
const concurrency = os.cpus().length * 4;
const writeFile = promisify(fs.writeFile);
if (typeof process.env.SCAN_DIR === 'undefined')
throw new Error('SCAN_DIR environment variable required');
function mapper(source) {
return new Promise((resolve, reject) => {
console.log('source', source);
const stream = fs.createReadStream(source);
const input = stream.pipe(trim());
const mbox = new Mbox(input);
const messages = [];
mbox.on('message', (message) => messages.push(message));
mbox.on('end', async () => {
try {
const basename = path.basename(source, path.extname(source));
const dir = path.dirname(source);
const mboxDir = path.join(dir, basename);
try {
await makeDir(mboxDir);
} catch (err) {
console.log('source', source, 'err', err);
if (err.code !== 'EEXIST') return reject(err);
}
await Promise.all(
messages.map(async (message, i) => {
try {
await writeFile(
path.join(mboxDir, `${i}.txt`),
message.toString()
);
} catch (err) {
console.error('message', message, 'i', i, 'err', err);
try {
await writeFile(
path.join(mboxDir, '..', `${i}.txt`),
message.toString()
);
} catch (err) {
console.error('message', message, 'i', i, 'err', err);
}
}
})
);
console.log(
`wrote ${source} with ${messages.length} messages to ${mboxDir}`
);
resolve();
} catch (err) {
console.log('source', source, 'err', err);
reject(err);
}
});
});
}
(async () => {
const sources = await readDirDeep(process.env.SCAN_DIR, {
patterns: MBOX_PATTERNS
});
console.log('sources.length', sources.length);
await pMap(sources, mapper, { concurrency });
})();