Debian Codegraph @

README.md

raw
1 # Lightning fast, asynchronous, streaming RDF for JavaScript
2 [![Build Status](https://github.com/rdfjs/N3.js/workflows/CI/badge.svg)](https://github.com/rdfjs/N3.js/actions)
3 [![Coverage Status](https://coveralls.io/repos/github/rdfjs/N3.js/badge.svg)](https://coveralls.io/github/rdfjs/N3.js)
4 [![npm version](https://badge.fury.io/js/n3.svg)](https://www.npmjs.com/package/n3)
5 [![DOI](https://zenodo.org/badge/3058202.svg)](https://zenodo.org/badge/latestdoi/3058202)
6
7 The N3.js library is an implementation of the [RDF.js low-level specification](http://rdf.js.org/) that lets you handle [RDF](https://www.w3.org/TR/rdf-primer/) in JavaScript easily.
8 It offers:
9
10 - [**Parsing**](#parsing) triples/quads from
11 [Turtle](https://www.w3.org/TR/turtle/),
12 [TriG](https://www.w3.org/TR/trig/),
13 [N-Triples](https://www.w3.org/TR/n-triples/),
14 [N-Quads](https://www.w3.org/TR/n-quads/),
15 [RDF*](https://blog.liu.se/olafhartig/2019/01/10/position-statement-rdf-star-and-sparql-star/)
16 and [Notation3 (N3)](https://www.w3.org/TeamSubmission/n3/)
17 - [**Writing**](#writing) triples/quads to
18 [Turtle](https://www.w3.org/TR/turtle/),
19 [TriG](https://www.w3.org/TR/trig/),
20 [N-Triples](https://www.w3.org/TR/n-triples/),
21 [N-Quads](https://www.w3.org/TR/n-quads/)
22 and [RDF*](https://blog.liu.se/olafhartig/2019/01/10/position-statement-rdf-star-and-sparql-star/)
23 - [**Storage**](#storing) of triples/quads in memory
24
25 Parsing and writing is:
26 - 🎛 **asynchronous** – triples arrive as soon as possible
27 - 🚰 **streaming** – streams are parsed as data comes in, so you can parse files larger than memory
28 - ⚡️ **fast** – triples are flying out at high speeds
29
30 ## Installation
31 For Node.js, N3.js comes as an [npm package](https://npmjs.org/package/n3).
32
33 ```Bash
34 $ npm install n3
35 ```
36
37 ```JavaScript
38 const N3 = require('n3');
39 ```
40
41 N3.js seamlessly works in browsers via [webpack](https://webpack.js.org/)
42 or [browserify](http://browserify.org/).
43 If you're unfamiliar with these tools,
44 you can read
45 [_webpack: Creating a Bundle – getting started_](https://webpack.js.org/guides/getting-started/#creating-a-bundle)
46 or
47 [_Introduction to browserify_](https://writingjavascript.org/posts/introduction-to-browserify).
48 You will need to create a "UMD bundle" and supply a name (e.g. with the `-s N3` option in browserify).
49
50 You can also load it via CDN:
51 ```html
52 <script src="https://unpkg.com/n3/browser/n3.min.js"></script>
53 ```
54
55 ## Creating triples/quads
56 N3.js follows the [RDF.js low-level specification](http://rdf.js.org/).
57
58 `N3.DataFactory` will give you the [factory](http://rdf.js.org/#datafactory-interface) functions to create triples and quads:
59
60 ```JavaScript
61 const { DataFactory } = N3;
62 const { namedNode, literal, defaultGraph, quad } = DataFactory;
63 const myQuad = quad(
64 namedNode('https://ruben.verborgh.org/profile/#me'),
65 namedNode('http://xmlns.com/foaf/0.1/givenName'),
66 literal('Ruben', 'en'),
67 defaultGraph(),
68 );
69 console.log(myQuad.termType); // Quad
70 console.log(myQuad.value); // ''
71 console.log(myQuad.subject.value); // https://ruben.verborgh.org/profile/#me
72 console.log(myQuad.object.value); // Ruben
73 console.log(myQuad.object.datatype.value); // http://www.w3.org/1999/02/22-rdf-syntax-ns#langString
74 console.log(myQuad.object.language); // en
75 ```
76
77 In the rest of this document, we will treat “triples” and “quads” equally:
78 we assume that a quad is simply a triple in a named or default graph.
79
80 ## Parsing
81
82 ### From an RDF document to quads
83
84 `N3.Parser` transforms Turtle, TriG, N-Triples, or N-Quads document into quads through a callback:
85 ```JavaScript
86 const parser = new N3.Parser();
87 parser.parse(
88 `PREFIX c: <http://example.org/cartoons#>
89 c:Tom a c:Cat.
90 c:Jerry a c:Mouse;
91 c:smarterThan c:Tom.`,
92 (error, quad, prefixes) => {
93 if (quad)
94 console.log(quad);
95 else
96 console.log("# That's all, folks!", prefixes);
97 });
98 ```
99 The callback's first argument is an optional error value, the second is a quad.
100 If there are no more quads,
101 the callback is invoked one last time with `null` for `quad`
102 and a hash of prefixes as third argument.
103 <br>
104 Pass a second callback to `parse` to retrieve prefixes as they are read.
105 <br>
106 If no callbacks are provided, parsing happens synchronously.
107
108 By default, `N3.Parser` parses a permissive superset of Turtle, TriG, N-Triples, and N-Quads.
109 <br>
110 For strict compatibility with any of those languages, pass a `format` argument upon creation:
111
112 ```JavaScript
113 const parser1 = new N3.Parser({ format: 'N-Triples' });
114 const parser2 = new N3.Parser({ format: 'application/trig' });
115 ```
116
117 Notation3 (N3) is supported _only_ through the `format` argument:
118
119 ```JavaScript
120 const parser3 = new N3.Parser({ format: 'N3' });
121 const parser4 = new N3.Parser({ format: 'Notation3' });
122 const parser5 = new N3.Parser({ format: 'text/n3' });
123 ```
124
125 It is possible to provide the base IRI of the document that you want to parse.
126 This is done by passing a `baseIRI` argument upon creation:
127 ```JavaScript
128 const parser = new N3.Parser({ baseIRI: 'http://example.org/' });
129 ```
130
131 By default, `N3.Parser` will prefix blank node labels with a `b{digit}_` prefix.
132 This is done to prevent collisions of unrelated blank nodes having identical
133 labels. The `blankNodePrefix` constructor argument can be used to modify the
134 prefix or, if set to an empty string, completely disable prefixing:
135 ```JavaScript
136 const parser = new N3.Parser({ blankNodePrefix: '' });
137 ```
138
139 ### From an RDF stream to quads
140
141 `N3.Parser` can parse [Node.js streams](http://nodejs.org/api/stream.html) as they grow,
142 returning quads as soon as they're ready.
143
144 ```JavaScript
145 const parser = new N3.Parser(),
146 rdfStream = fs.createReadStream('cartoons.ttl');
147 parser.parse(rdfStream, console.log);
148 ```
149
150 `N3.StreamParser` is a [Node.js stream](http://nodejs.org/api/stream.html) and [RDF.js Sink](http://rdf.js.org/#sink-interface) implementation.
151 This solution is ideal if your consumer is slower,
152 since source data is only read when the consumer is ready.
153
154 ```JavaScript
155 const streamParser = new N3.StreamParser(),
156 rdfStream = fs.createReadStream('cartoons.ttl');
157 rdfStream.pipe(streamParser);
158 streamParser.pipe(new SlowConsumer());
159
160 function SlowConsumer() {
161 const writer = new require('stream').Writable({ objectMode: true });
162 writer._write = (quad, encoding, done) => {
163 console.log(quad);
164 setTimeout(done, 1000);
165 };
166 return writer;
167 }
168 ```
169
170 A dedicated `prefix` event signals every prefix with `prefix` and `term` arguments.
171
172 ## Writing
173
174 ### From quads to a string
175
176 `N3.Writer` serializes quads as an RDF document.
177 Write quads through `addQuad`.
178
179 ```JavaScript
180 const writer = new N3.Writer({ prefixes: { c: 'http://example.org/cartoons#' } });
181 writer.addQuad(
182 namedNode('http://example.org/cartoons#Tom'),
183 namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
184 namedNode('http://example.org/cartoons#Cat')
185 );
186 writer.addQuad(quad(
187 namedNode('http://example.org/cartoons#Tom'),
188 namedNode('http://example.org/cartoons#name'),
189 literal('Tom')
190 ));
191 writer.end((error, result) => console.log(result));
192 ```
193
194 By default, `N3.Writer` writes Turtle (or TriG if some quads are in a named graph).
195 <br>
196 To write N-Triples (or N-Quads) instead, pass a `format` argument upon creation:
197
198 ```JavaScript
199 const writer1 = new N3.Writer({ format: 'N-Triples' });
200 const writer2 = new N3.Writer({ format: 'application/trig' });
201 ```
202
203 ### From quads to an RDF stream
204
205 `N3.Writer` can also write quads to a Node.js stream.
206
207 ```JavaScript
208 const writer = new N3.Writer(process.stdout, { end: false, prefixes: { c: 'http://example.org/cartoons#' } });
209 writer.addQuad(
210 namedNode('http://example.org/cartoons#Tom'),
211 namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
212 namedNode('http://example.org/cartoons#Cat')
213 );
214 writer.addQuad(quad(
215 namedNode('http://example.org/cartoons#Tom'),
216 namedNode('http://example.org/cartoons#name'),
217 literal('Tom')
218 ));
219 writer.end();
220 ```
221
222 ### From a quad stream to an RDF stream
223
224 `N3.StreamWriter` is a [Node.js stream](http://nodejs.org/api/stream.html) and [RDF.js Sink](http://rdf.js.org/#sink-interface) implementation.
225
226 ```JavaScript
227 const streamParser = new N3.StreamParser(),
228 inputStream = fs.createReadStream('cartoons.ttl'),
229 streamWriter = new N3.StreamWriter({ prefixes: { c: 'http://example.org/cartoons#' } });
230 inputStream.pipe(streamParser);
231 streamParser.pipe(streamWriter);
232 streamWriter.pipe(process.stdout);
233 ```
234
235 ### Blank nodes and lists
236 You might want to use the `[…]` and list `(…)` notations of Turtle and TriG.
237 However, a streaming writer cannot create these automatically:
238 the shorthand notations are only possible if blank nodes or list heads are not used later on,
239 which can only be determined conclusively at the end of the stream.
240
241 The `blank` and `list` functions allow you to create them manually instead:
242 ```JavaScript
243 const writer = new N3.Writer({ prefixes: { c: 'http://example.org/cartoons#',
244 foaf: 'http://xmlns.com/foaf/0.1/' } });
245 writer.addQuad(
246 writer.blank(
247 namedNode('http://xmlns.com/foaf/0.1/givenName'),
248 literal('Tom', 'en')),
249 namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
250 namedNode('http://example.org/cartoons#Cat')
251 );
252 writer.addQuad(quad(
253 namedNode('http://example.org/cartoons#Jerry'),
254 namedNode('http://xmlns.com/foaf/0.1/knows'),
255 writer.blank([{
256 predicate: namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'),
257 object: namedNode('http://example.org/cartoons#Cat'),
258 },{
259 predicate: namedNode('http://xmlns.com/foaf/0.1/givenName'),
260 object: literal('Tom', 'en'),
261 }])
262 ));
263 writer.addQuad(
264 namedNode('http://example.org/cartoons#Mammy'),
265 namedNode('http://example.org/cartoons#hasPets'),
266 writer.list([
267 namedNode('http://example.org/cartoons#Tom'),
268 namedNode('http://example.org/cartoons#Jerry'),
269 ])
270 );
271 writer.end((error, result) => console.log(result));
272 ```
273
274 ## Storing
275
276 `N3.Store` allows you to store triples in memory and find them fast.
277
278 In this example, we create a new store and add the triples `:Pluto a :Dog.` and `:Mickey a :Mouse`.
279 <br>
280 Then, we find triples with `:Mickey` as subject.
281
282 ```JavaScript
283 const store = new N3.Store();
284 store.add(
285 namedNode('http://ex.org/Pluto'),
286 namedNode('http://ex.org/type'),
287 namedNode('http://ex.org/Dog')
288 );
289 store.add(
290 namedNode('http://ex.org/Mickey'),
291 namedNode('http://ex.org/type'),
292 namedNode('http://ex.org/Mouse')
293 );
294
295 // Retrieve all quads
296 for (const quad of store)
297 console.log(quad);
298 // Retrieve Mickey's quads
299 for (const quad of store.match(namedNode('http://ex.org/Mickey'), null, null))
300 console.log(quad);
301 ```
302
303 ### [`DatasetCore` Interface](https://rdf.js.org/dataset-spec/#datasetcore-interface)
304 This store adheres to the `DatasetCore` interface which exposes the following properties
305
306 Attributes:
307 - `size` — A non-negative integer that specifies the number of quads in the set.
308
309 Methods:
310 - `add` — Adds the specified quad to the dataset. Existing quads, as defined in `Quad.equals`, will be ignored.
311 - `delete` — Removes the specified quad from the dataset.
312 - `has` — Determines whether a dataset includes a certain quad.
313 - `match` — Returns a new dataset that is comprised of all quads in the current instance matching the given arguments.
314 - `[Symbol.iterator]` — Implements the iterator protocol to allow iteration over all `quads` in the dataset as in the example above.
315
316 ### Addition and deletion of quads
317 The store provides the following manipulation methods in addition to implementing the standard [`DatasetCore` Interface](https://rdf.js.org/dataset-spec/#datasetcore-interface)
318 ([documentation](http://rdfjs.github.io/N3.js/docs/N3Store.html)):
319 - `addQuad` to insert one quad
320 - `addQuads` to insert an array of quads
321 - `removeQuad` to remove one quad
322 - `removeQuads` to remove an array of quads
323 - `remove` to remove a stream of quads
324 - `removeMatches` to remove all quads matching the given pattern
325 - `deleteGraph` to remove all quads with the given graph
326 - `createBlankNode` returns an unused blank node identifier
327
328 ### Searching quads or entities
329 The store provides the following search methods
330 ([documentation](http://rdfjs.github.io/N3.js/docs/N3Store.html)):
331 - `readQuads` returns a generator of quads matching the given pattern
332 - `getQuads` returns an array of quads matching the given pattern
333 - `match` returns a stream of quads matching the given pattern
334 - `countQuads` counts the number of quads matching the given pattern
335 - `forEach` executes a callback on all matching quads
336 - `every` returns whether a callback on matching quads always returns true
337 - `some` returns whether a callback on matching quads returns true at least once
338 - `getSubjects` returns an array of unique subjects occurring in matching quads
339 - `forSubjects` executes a callback on unique subjects occurring in matching quads
340 - `getPredicates` returns an array of unique predicates occurring in matching quad
341 - `forPredicates` executes a callback on unique predicates occurring in matching quads
342 - `getObjects` returns an array of unique objects occurring in matching quad
343 - `forObjects` executes a callback on unique objects occurring in matching quads
344 - `getGraphs` returns an array of unique graphs occurring in matching quad
345 - `forGraphs` executes a callback on unique graphs occurring in matching quads
346
347 ## Compatibility
348 ### Format specifications
349 The N3.js parser and writer is fully compatible with the following W3C specifications:
350 - [RDF 1.1 Turtle](https://www.w3.org/TR/turtle/)
351 – [EARL report](https://raw.githubusercontent.com/rdfjs/N3.js/earl/n3js-earl-report-turtle.ttl)
352 - [RDF 1.1 TriG](https://www.w3.org/TR/trig/)
353 – [EARL report](https://raw.githubusercontent.com/rdfjs/N3.js/earl/n3js-earl-report-trig.ttl)
354 - [RDF 1.1 N-Triples](https://www.w3.org/TR/n-triples/)
355 – [EARL report](https://raw.githubusercontent.com/rdfjs/N3.js/earl/n3js-earl-report-ntriples.ttl)
356 - [RDF 1.1 N-Quads](https://www.w3.org/TR/n-quads/)
357 – [EARL report](https://raw.githubusercontent.com/rdfjs/N3.js/earl/n3js-earl-report-nquads.ttl)
358
359 In addition, the N3.js parser also supports [Notation3 (N3)](https://www.w3.org/TeamSubmission/n3/) (no official specification yet).
360
361 The N3.js parser and writer are also fully compatible with the RDF* variants
362 of the W3C specifications.
363
364 The default mode is permissive
365 and allows a mixture of different syntaxes, including RDF*.
366 Pass a `format` option to the constructor with the name or MIME type of a format
367 for strict, fault-intolerant behavior.
368 If a format string contains `star` or `*`
369 (e.g., `turtlestar` or `TriG*`),
370 RDF* support for that format will be enabled.
371
372 ### Interface specifications
373 The N3.js submodules are compatible with the following [RDF.js](http://rdf.js.org) interfaces:
374
375 - `N3.DataFactory` implements
376 [`DataFactory`](http://rdf.js.org/data-model-spec/#datafactory-interface)
377 - the terms it creates implement [`Term`](http://rdf.js.org/data-model-spec/#term-interface)
378 and one of
379 [`NamedNode`](http://rdf.js.org/data-model-spec/#namednode-interface),
380 [`BlankNode`](http://rdf.js.org/data-model-spec/#blanknode-interface),
381 [`Literal`](http://rdf.js.org/data-model-spec/#literal-interface),
382 [`Variable`](http://rdf.js.org/data-model-spec/#variable-interface),
383 [`DefaultGraph`](http://rdf.js.org/data-model-spec/#defaultgraph-interface)
384 - the triples/quads it creates implement
385 [`Term`](http://rdf.js.org/data-model-spec/#term-interface),
386 [`Triple`](http://rdf.js.org/data-model-spec/#triple-interface)
387 and
388 [`Quad`](http://rdf.js.org/data-model-spec/#quad-interface)
389 - `N3.StreamParser` implements
390 [`Stream`](http://rdf.js.org/stream-spec/#stream-interface)
391 and
392 [`Sink`](http://rdf.js.org/stream-spec/#sink-interface)
393 - `N3.StreamWriter` implements
394 [`Stream`](http://rdf.js.org/stream-spec/#stream-interface)
395 and
396 [`Sink`](http://rdf.js.org/stream-spec/#sink-interface)
397 - `N3.Store` implements
398 [`Store`](http://rdf.js.org/stream-spec/#store-interface)
399 [`Source`](http://rdf.js.org/stream-spec/#source-interface)
400 [`Sink`](http://rdf.js.org/stream-spec/#sink-interface)
401 [`DatasetCore`](https://rdf.js.org/dataset-spec/#datasetcore-interface)
402
403 ## License and contributions
404 The N3.js library is copyrighted by [Ruben Verborgh](https://ruben.verborgh.org/)
405 and released under the [MIT License](https://github.com/rdfjs/N3.js/blob/master/LICENSE.md).
406
407 Contributions are welcome, and bug reports or pull requests are always helpful.
408 If you plan to implement a larger feature, it's best to contact me first.