-
Notifications
You must be signed in to change notification settings - Fork 3
/
createDictDatabase.js
48 lines (42 loc) · 1.28 KB
/
createDictDatabase.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
const path = require('path')
const Database = require('better-sqlite3')
const cheerio = require('cheerio')
const { createReadStream } = require('fs')
const { Separator } = require('./separator')
const doubleQuote = str => str.replace(/'/g, "''")
function createDictDatabase({ input: rawml, output: database }) {
return new Promise((resolve, reject) => {
const db = new Database(database)
db.exec('CREATE TABLE dictionary(word text, meaning text)')
const src = createReadStream(rawml)
src
.pipe(new Separator({ separator: '<hr/>' }))
.on('data', chunk => {
let html = chunk.toString().trim()
let $ = cheerio.load(html)
let $word = $('word')
if (!$word.length) {
return
}
let words = $word
.map((_, word) => {
word = $(word)
word.find('sup').remove()
return word.text().replace(/,?\s*$/, '')
})
.get()
const sql = `INSERT INTO dictionary (word, meaning) VALUES (
'${doubleQuote(words.join('|'))}',
'${doubleQuote(html)}')`
db.exec(sql)
})
.on('end', () => {
console.log('Dictionary saved in dict.db.')
db.close()
resolve()
})
})
}
module.exports = {
createDictDatabase
}