-
Notifications
You must be signed in to change notification settings - Fork 0
/
RdfFileConnection.js
79 lines (67 loc) · 2.45 KB
/
RdfFileConnection.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
import fs from 'node:fs';
import N3 from 'n3';
const DEFAULT_BUFFER_SIZE = 10000000;
async function turtleToNT(turtleStr, options = {}) {
const format = options.format === 'application/n-quads' && options.outputGraphname ?
'application/n-quads' :
'application/n-triples';
const turtleParser = new N3.Parser();
const quadwriter = new N3.Writer({format});
return new Promise((resolve, reject) => {
turtleParser.parse(turtleStr, (error, quad, prefixes) => {
if (error) {
reject(error);
}
if (quad) {
if (format === 'application/n-quads') {
quadwriter.addQuad(
quad.subject, quad.predicate, quad.object,
N3.DataFactory.namedNode(options.outputGraphname));
} else {
quadwriter.addQuad(quad);
}
} else {
quadwriter.end((error, result) => {
if (error) {
reject(error);
} else {
resolve(result);
}
});
}
})
});
}
export default class RdfFileConnection {
constructor(filePath, options = {}) {
this.filePath = filePath;
this.options = options;
this.buffer = Buffer.allocUnsafe(options.bufferSize || DEFAULT_BUFFER_SIZE);
this.bufferPosition = 0;
}
async delete() {
fs.promises.writeFile(this.filePath, '');
}
async post(turtleStr) {
const nTriplesStr = await turtleToNT(this.options.preamble + '\n' + turtleStr, this.options);
await this.addToBuffer(nTriplesStr);
}
async addToBuffer(nTriplesStr) {
const newDataBuffer = Buffer.from(nTriplesStr);
const writtenBytes = newDataBuffer.copy(this.buffer, this.bufferPosition);
this.bufferPosition += writtenBytes;
if (writtenBytes < newDataBuffer.length) {
await this._flush(newDataBuffer.toString('utf-8', writtenBytes));
}
}
async _flush(lastNTriplesStr) {
await fs.promises.appendFile(this.filePath, this.bufferPosition >= this.buffer.byteLength ? this.buffer : this.buffer.slice(0, this.bufferPosition));
this.bufferPosition = 0;
if (lastNTriplesStr) {
await this.addToBuffer(lastNTriplesStr);
}
}
async sync() {
await this._flush();
}
}