### Full Example: Extracting and Applying N3 Rules Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-reasoner.md Demonstrates how to parse N3 data, extract rules using `getRulesFromDataset`, and apply reasoning with `Reasoner`. This example shows rule extraction from a store and verification of derived facts. ```javascript const { Reasoner, getRulesFromDataset, Parser, Store } = require('n3'); const parser = new Parser({ format: 'n3' }); const ttl = `@prefix : . @prefix log: . # Facts :alice a :Parent . :bob a :Child . :alice :parentOf :bob . # Rule: Parent of child is ancestor { ?x :parentOf ?y } => { ?x :ancestorOf ?y } . `; const quads = parser.parse(ttl); const store = new Store(quads); // Extract rules from store const rules = getRulesFromDataset(store); console.log(rules.length); // 1 rule extracted // Apply reasoning const reasoner = new Reasoner(store); reasoner.reason(rules); // Verify derived facts const ancestorQuads = store.getQuads( null, parser._factory.namedNode('http://example.org/ancestorOf'), null ); console.log(ancestorQuads.length); // Will include derived facts ``` -------------------------------- ### Configure Parser with Custom RDF/JS Factory Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Example of initializing the Parser with a custom RDF/JS factory for creating terms and quads. ```javascript // With custom factory const parser4 = new Parser({ factory: customRDFJSFactory }); ``` -------------------------------- ### Importing DataFactory and Core Functions Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-datafactory.md Import the DataFactory singleton and essential RDF term creation functions from the n3 library. This setup is assumed for all subsequent examples. ```javascript const { DataFactory, namedNode, literal, blankNode, variable, defaultGraph, quad } = require('n3'); ``` -------------------------------- ### Pipe StreamParser with StreamWriter Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-streaming.md Example demonstrating piping an input file through a StreamParser and then a StreamWriter to convert formats. ```javascript const fs = require('fs'); const { StreamParser, StreamWriter } = require('n3'); const parser = new StreamParser({ format: 'turtle' }); const writer = new StreamWriter({ format: 'n-quads' }); fs.createReadStream('input.ttl') .pipe(parser) .pipe(writer) .pipe(fs.createWriteStream('output.nq')); ``` -------------------------------- ### Initialize N3Reasoner with a Store Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-reasoner.md Instantiate the Reasoner by providing an N3Store. This example demonstrates parsing N3 data, including rules, and adding them to the store before initializing the Reasoner. ```javascript const { Reasoner, Store, Parser } = require('n3'); const parser = new Parser(); const store = new Store(); // Parse N3 with rules const quads = parser.parse( ` @prefix : . @prefix log: . :alice a :Person . {?x a :Person} => {?x a :Agent} . ` ); quads.forEach(quad => store.addQuad(quad)); const reasoner = new Reasoner(store); ``` -------------------------------- ### Install N3.js via npm Source: https://github.com/rdfjs/n3.js/blob/main/README.md Use this command to install the N3.js package in your Node.js project. ```bash npm install n3 ``` -------------------------------- ### Configure Parser for N3 with Explicit Quantifiers Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Example of initializing the Parser for N3 format, enabling explicit quantifiers, and setting a base IRI. ```javascript // N3 with quantifiers const parser3 = new Parser({ format: 'n3', explicitQuantifiers: true, baseIRI: 'http://example.org/rules' }); ``` -------------------------------- ### Configure Parser for N-Quads with Custom Blank Node Prefix Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Example of initializing the Parser for N-Quads format and setting a custom prefix for auto-generated blank nodes. ```javascript // N-Quads with custom blank node prefix const parser2 = new Parser({ format: 'n-quads', blankNodePrefix: 'MyBlankNodes' }); ``` -------------------------------- ### Configure Turtle Writer with Prefixes Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Example of creating a Turtle writer with initial namespace prefixes. Ensure the 'fs' module is required for file stream operations. ```javascript const fs = require('fs'); // Turtle with prefixes const writer1 = new Writer(fs.createWriteStream('out.ttl'), { format: 'turtle', prefixes: { ex: 'http://example.org/', foaf: 'http://xmlns.com/foaf/0.1/' } }); ``` -------------------------------- ### Advanced RDFS Reasoning Example Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-reasoner.md An advanced example showcasing RDFS reasoning using N3.js. It includes rules for RDFS subClassOf transitivity and type inheritance, demonstrating how to add ontology and data to a store and then perform reasoning. ```javascript const { Reasoner, Store, DataFactory } = require('n3'); const store = new Store(); const reasoner = new Reasoner(store); const rdf = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'; const rdfs = 'http://www.w3.org/2000/01/rdf-schema#'; const ex = 'http://example.org/'; // RDFS rule: subClassOf transitivity const subClassTransitive = { premise: [ DataFactory.quad( DataFactory.variable('a'), DataFactory.namedNode(rdfs + 'subClassOf'), DataFactory.variable('b') ), DataFactory.quad( DataFactory.variable('b'), DataFactory.namedNode(rdfs + 'subClassOf'), DataFactory.variable('c') ) ], conclusion: [ DataFactory.quad( DataFactory.variable('a'), DataFactory.namedNode(rdfs + 'subClassOf'), DataFactory.variable('c') ) ] }; // RDFS rule: type inheritance const typeInheritance = { premise: [ DataFactory.quad( DataFactory.variable('x'), DataFactory.namedNode(rdf + 'type'), DataFactory.variable('a') ), DataFactory.quad( DataFactory.variable('a'), DataFactory.namedNode(rdfs + 'subClassOf'), DataFactory.variable('b') ) ], conclusion: [ DataFactory.quad( DataFactory.variable('x'), DataFactory.namedNode(rdf + 'type'), DataFactory.variable('b') ) ] }; // Add ontology and data store.addQuad(DataFactory.quad( DataFactory.namedNode(ex + 'Cat'), DataFactory.namedNode(rdfs + 'subClassOf'), DataFactory.namedNode(ex + 'Animal') )); store.addQuad(DataFactory.quad( DataFactory.namedNode(ex + 'Fluffy'), DataFactory.namedNode(rdf + 'type'), DataFactory.namedNode(ex + 'Cat') )); // Reason reasoner.reason([subClassTransitive, typeInheritance]); // Now Fluffy is inferred to be an Animal const result = store.has( DataFactory.namedNode(ex + 'Fluffy'), DataFactory.namedNode(rdf + 'type'), DataFactory.namedNode(ex + 'Animal') ); console.log(result); // true ``` -------------------------------- ### Configure N-Quads Writer to String Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Example of creating an N-Quads writer. This writer does not require an output stream if writing to a string is intended. ```javascript // N-Quads to string const writer2 = new Writer({ format: 'n-quads' }); ``` -------------------------------- ### CommonJS / Node.js Entry Point Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/module-structure.md Import the N3 library using require for CommonJS environments. This example shows how to access individual exports. ```javascript const N3 = require('n3'); // Access any export const { Parser, Store, Writer, Lexer, StreamParser, StreamWriter } = require('n3'); ``` -------------------------------- ### Example: Creating and Inspecting a Named Node Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-datafactory.md Demonstrates how to create named nodes using `DataFactory.namedNode` and access their `termType` and `value` properties. This is useful for representing URIs in RDF. ```javascript const ex = DataFactory.namedNode('http://example.org/'); const person = DataFactory.namedNode('http://example.org/alice'); console.log(person.termType); // 'NamedNode' console.log(person.value); // 'http://example.org/alice' ``` -------------------------------- ### Configure Parser for Turtle with Base IRI Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Example of initializing the Parser for Turtle format with a specified base IRI for resolving relative IRIs. ```javascript // Turtle with base IRI const parser1 = new Parser({ baseIRI: 'http://example.org/', format: 'turtle' }); ``` -------------------------------- ### ES Modules Entry Point Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/module-structure.md Import the N3 library using ES module syntax for modern JavaScript environments. This example demonstrates named imports. ```javascript import { Parser, Store, Writer, Lexer, StreamParser, StreamWriter } from 'n3'; ``` -------------------------------- ### Get All Subjects and Specific Subjects from N3.js Store Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Demonstrates retrieving all subjects using wildcards and specific subjects by providing predicate and object terms. ```javascript const allSubjects = store.getSubjects(null, null); const subjects = store.getSubjects(rdfType, personType); ``` -------------------------------- ### Configure TriG Writer with Base IRI and Prefixes Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Example of creating a TriG writer with a base IRI and a default namespace prefix. This is useful for abbreviating relative IRIs. ```javascript // TriG with base IRI const writer3 = new Writer(fs.createWriteStream('out.trig'), { format: 'trig', baseIRI: 'http://example.org/data/', prefixes: { '': 'http://example.org/' } }); ``` -------------------------------- ### N3 Rule Syntax Example Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-reasoner.md Illustrates the basic syntax for defining N3 rules, where premise quads imply conclusion quads. This syntax is used within N3 data files. ```n3 @prefix log: . { ?x a :Parent } => { ?x a :Ancestor } . ``` -------------------------------- ### Apply Transitive Closure Rules Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-reasoner.md Demonstrates applying multiple rules to achieve transitive reasoning. This example defines a direct ancestor rule and a transitive ancestor rule, which are chained by the reasoner. ```javascript const { Reasoner, Store, DataFactory } = require('n3'); const store = new Store(); const reasoner = new Reasoner(store); const parentOf = DataFactory.namedNode('http://example.org/parentOf'); // Rule 1: Direct ancestor const directRule = { premise: [ DataFactory.quad( DataFactory.variable('x'), parentOf, DataFactory.variable('y') ) ], conclusion: [ DataFactory.quad( DataFactory.variable('x'), DataFactory.namedNode('http://example.org/ancestorOf'), DataFactory.variable('y') ) ] }; // Rule 2: Transitive ancestor (ancestor of ancestor) const transitiveRule = { premise: [ DataFactory.quad( DataFactory.variable('x'), DataFactory.namedNode('http://example.org/ancestorOf'), DataFactory.variable('y') ), DataFactory.quad( DataFactory.variable('y'), DataFactory.namedNode('http://example.org/ancestorOf'), DataFactory.variable('z') ) ], conclusion: [ DataFactory.quad( DataFactory.variable('x'), DataFactory.namedNode('http://example.org/ancestorOf'), DataFactory.variable('z') ) ] }; // Add data const alice = DataFactory.namedNode('http://example.org/alice'); const bob = DataFactory.namedNode('http://example.org/bob'); const charlie = DataFactory.namedNode('http://example.org/charlie'); store.addQuad(DataFactory.quad(alice, parentOf, bob)); store.addQuad(DataFactory.quad(bob, parentOf, charlie)); // Apply rules reasoner.reason([directRule, transitiveRule]); // Now store contains: // alice parentOf bob (original) // bob parentOf charlie (original) // alice ancestorOf bob (from directRule) // bob ancestorOf charlie (from directRule) // alice ancestorOf charlie (from transitiveRule) ``` -------------------------------- ### Add Namespace Prefix to N3Writer Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-writer.md Shows how to declare namespace prefixes for IRI abbreviation, including examples using string IRIs and NamedNode objects. ```javascript writer.addPrefix('ex', 'http://example.org/'); writer.addPrefix('foaf', 'http://xmlns.com/foaf/0.1/'); writer.addPrefix('rdf', DataFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#')); ``` -------------------------------- ### Example: Convert External Term Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/types.md Demonstrates using DataFactory.fromTerm to convert an external RDF.js term into an N3.js term. This is useful when working with data from different RDF libraries. ```javascript const externalTerm = otherFactory.namedNode('http://example.org/'); const n3Term = DataFactory.fromTerm(externalTerm); ``` -------------------------------- ### Add Single Quad to N3Writer Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-writer.md Shows how to add individual quads to the writer using separate terms, a quad object, or specifying a named graph. Includes an example of a callback for when the quad is written. ```javascript const { Writer, DataFactory } = require('n3'); const { namedNode, literal } = DataFactory; const writer = new Writer(); // Using separate terms writer.addQuad( namedNode('http://example.org/alice'), namedNode('http://xmlns.com/foaf/0.1/name'), literal('Alice') ); // Using a quad object const quad = DataFactory.quad( namedNode('http://example.org/alice'), namedNode('http://xmlns.com/foaf/0.1/age'), literal('30'), DataFactory.defaultGraph() ); writer.addQuad(quad, () => { console.log('Quad written'); }); // With named graph writer.addQuad( namedNode('http://example.org/bob'), namedNode('http://example.org/knows'), namedNode('http://example.org/alice'), namedNode('http://example.org/data'), () => { console.log('Done'); } ); ``` -------------------------------- ### Instantiate N3Parser with Options Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Demonstrates how to create a new N3Parser instance with various configuration options. ```javascript new Parser(options) ``` -------------------------------- ### N3Store Basic Initialization Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Initialize a new N3Store instance. ```javascript const store1 = new Store(); ``` -------------------------------- ### N3Store Initialization with Quads Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Initialize a new N3Store instance with initial quads. ```javascript const store2 = new Store(quads); ``` -------------------------------- ### Initialize N3Store Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Create a new N3Store instance. You can initialize it as an empty store, with an array of quads, or with custom options like a factory. ```javascript const { Store, DataFactory } = require('n3'); // Empty store const store = new Store(); // Store with initial quads const quads = [ DataFactory.quad(s1, p1, o1), DataFactory.quad(s2, p2, o2), ]; const populatedStore = new Store(quads); // Custom factory const customStore = new Store(quads, { factory: customFactory }); ``` -------------------------------- ### Get N3Store Size Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Access the 'size' property to retrieve the total number of quads currently stored in the N3Store. ```javascript const store = new Store([q1, q2, q3]); console.log(store.size); // 3 ``` -------------------------------- ### Create and Populate N3.js Store Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/quick-reference.md Demonstrates how to initialize an N3.js store and add individual or multiple quads. ```javascript const { Store } = require('n3'); const store = new Store(); // Add individual quad store.addQuad(subject, predicate, object, graph); // Add complete quad object store.addQuad(quad); // Add multiple quads store.addQuads([quad1, quad2, quad3]); ``` -------------------------------- ### N3Store Initialization with Custom Factory Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Initialize a new N3Store instance using a custom RDF.js factory for creating terms and quads. ```javascript const store3 = new Store(null, { factory: customFactory }); ``` -------------------------------- ### Get Predicates from N3.js Store Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Retrieves all predicates matching a given subject, object, and graph pattern. Wildcards can be used for any parameter. ```javascript const predicates = store.getPredicates(subject, object, graph); ``` -------------------------------- ### Get Quads as Array Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Returns an array containing all quads that match the specified pattern. Useful for retrieving a collection of matching quads. ```javascript const quads = store.getQuads(subject, predicate, object, graph); ``` ```javascript const allQuads = store.getQuads(null, null, null); const subjectQuads = store.getQuads(alice, null, null); ``` -------------------------------- ### N3Store Constructor Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Initializes a new N3Store instance. It can be populated with initial quads and configured with options like a custom RDF.js factory or an entity index. ```APIDOC ## new Store(quads, options) ### Description Initializes a new N3Store instance. It can be populated with initial quads and configured with options like a custom RDF.js factory or an entity index. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **quads** (Array, iterable) - Optional - Initial quads to add to the store. If the first parameter is not an array/iterable (no `.match()` method), it's treated as options. - **options** (object) - Optional - Configuration object. Defaults to {}. - **options.factory** (object) - Optional - RDF.js factory for creating terms. Defaults to N3DataFactory. - **options.entityIndex** (N3EntityIndex) - Optional - Entity index for memory optimization. Defaults to new N3EntityIndex(). ### Request Example ```javascript const { Store, DataFactory } = require('n3'); // Empty store const store = new Store(); // Store with initial quads const quads = [ DataFactory.quad(s1, p1, o1), DataFactory.quad(s2, p2, o2), ]; const populatedStore = new Store(quads); // Custom factory const customStore = new Store(quads, { factory: customFactory }); ``` ### Response None ### Response Example None ``` -------------------------------- ### N3 Rule for Reasoning Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/README.md Example of an N3 rule using the `log:implies` predicate to define inference logic. Rules are applied repeatedly. ```n3 { ?x a :Parent } => { ?x a :Ancestor } . ``` -------------------------------- ### Building Queries with Prefixes Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-util.md Demonstrates how to use the `prefixes` utility function to manage prefixes for building SPARQL queries with N3.js. ```javascript const { Parser, Store, Util } = require('n3'); // Create prefix functions const p = Util.prefixes({ rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', rdfs: 'http://www.w3.org/2000/01/rdf-schema#', ex: 'http://example.org/' }); const store = new Store(); // Query using prefixes const rdfType = p('rdf')('type'); const person = p('ex')('Person'); const name = p('ex')('name'); const people = store.getSubjects(rdfType, person); people.forEach(subject => { const names = store.getObjects(subject, name); names.forEach(n => console.log(n.value)); }); ``` -------------------------------- ### Parse and Store RDF Quads Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/module-structure.md Use this pattern to parse an RDF string into quads and add them to an N3 Store. Ensure 'n3' is installed and imported. ```javascript const { Parser, Store } = require('n3'); const parser = new Parser(); const store = new Store(); const quads = parser.parse(ttlString); quads.forEach(quad => store.addQuad(quad)); ``` -------------------------------- ### N3Store Initialization with Shared Entity Index Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Initialize N3Store instances using a shared entity index for optimization across multiple stores. ```javascript const index = new N3EntityIndex(); const store4 = new Store(null, { entityIndex: index }); const store5 = new Store(null, { entityIndex: index }); ``` -------------------------------- ### Browser Entry Point (UMD Bundle) Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/module-structure.md Include the N3.js UMD bundle script in an HTML file for browser usage. The library is then available globally as `N3`. ```html ``` -------------------------------- ### Get Objects from N3.js Store Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Retrieves all objects matching a given subject, predicate, and graph pattern. Wildcards can be used for any parameter to match all values. ```javascript const objects = store.getObjects(subject, predicate, graph); ``` -------------------------------- ### Configure Writer to Not Auto-End Stream Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Example of creating a writer where the output stream is not automatically ended when the finish() method is called. This requires a pre-existing stream object. ```javascript // Don't auto-end stream const writer4 = new Writer(myStream, { end: false }); ``` -------------------------------- ### Importing N3.js Modules Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/README.md Demonstrates how to import all available classes, data factory, term types, quad types, and helper functions from the main entry point of the n3 library. ```javascript const { // Classes Parser, Writer, Store, Reasoner, StreamParser, StreamWriter, Lexer, BaseIRI, StoreFactory, EntityIndex, // DataFactory DataFactory, // Term types Term, NamedNode, BlankNode, Literal, Variable, DefaultGraph, // Quad Quad, Triple, // Helper functions Util, termFromId, termToId, getRulesFromDataset } = require('n3'); ``` -------------------------------- ### N3Reasoner Constructor Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-reasoner.md Initializes a new N3Reasoner instance with a given N3Store. The store should contain the triple data to be reasoned over. ```APIDOC ## new Reasoner(store) ### Description Initializes a new N3Reasoner instance with a given N3Store. The store should contain the triple data to be reasoned over. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **store** (N3Store) - Required - The store containing the triple data ### Request Example ```javascript const { Reasoner, Store, Parser } = require('n3'); const parser = new Parser(); const store = new Store(); // Parse N3 with rules const quads = parser.parse(` @prefix : . @prefix log: . :alice a :Person . {?x a :Person} => {?x a :Agent} . `); quads.forEach(quad => store.addQuad(quad)); const reasoner = new Reasoner(store); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Instantiate N3Writer Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-writer.md Demonstrates creating a Writer instance for writing to a file stream, collecting output as a string, or specifying a particular format like N-Quads. ```javascript const { Writer } = require('n3'); const fs = require('fs'); // Write to file const fileStream = fs.createWriteStream('output.ttl'); const fileWriter = new Writer(fileStream, { prefixes: { ex: 'http://example.org/', foaf: 'http://xmlns.com/foaf/0.1/' } }); // Collect output as string (no stream) const stringWriter = new Writer({ format: 'turtle', baseIRI: 'http://example.org/' }); // With specific format const nQuadsWriter = new Writer(fs.createWriteStream('output.nq'), { format: 'n-quads' }); ``` -------------------------------- ### Initialize StreamWriter with Options Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md The StreamWriter constructor accepts options similar to N3Writer, such as format, prefixes, and baseIRI. Use this to configure output format and namespace prefixes. ```javascript new StreamWriter(options) ``` -------------------------------- ### Get Subjects from N3.js Store Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Retrieves all subjects matching a given predicate, object, and graph pattern. Use wildcards (null/undefined) for any parameter to match all values. ```javascript const subjects = store.getSubjects(predicate, object, graph); ``` -------------------------------- ### Instantiate N3StreamParser Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-streaming.md Create a new N3StreamParser instance. Options can specify the base IRI, document format, RDF.js factory, and blank node prefix. ```javascript const { StreamParser } = require('n3'); // Basic stream parser const parser = new StreamParser(); // With format specification const turtleParser = new StreamParser({ baseIRI: 'http://example.org/', format: 'turtle' }); // With comment support const commentParser = new StreamParser({ format: 'n3', comments: true }); ``` -------------------------------- ### Get the Default Graph Singleton Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-datafactory.md DataFactory.defaultGraph() returns the singleton default graph term. This method is useful for ensuring you are always referencing the same default graph instance. ```javascript const dg = DataFactory.defaultGraph(); ``` ```javascript const dg = DataFactory.defaultGraph(); console.log(dg.termType); // 'DefaultGraph' console.log(dg.value); // '' console.log(dg === DataFactory.defaultGraph()); // true (singleton) ``` -------------------------------- ### Store Configuration Options Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/quick-reference.md Configure the N3.js store with options for the data factory and entity index. ```javascript new Store(quads, { factory: N3DataFactory, entityIndex: new N3EntityIndex() }) ``` -------------------------------- ### Instantiate N3.js StreamWriter Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-streaming.md Create a new StreamWriter instance. Options can configure the output format, prefixes, and base IRI. ```javascript const { StreamWriter } = require('n3'); // Basic stream writer const writer = new StreamWriter(); // Turtle with prefixes const turtleWriter = new StreamWriter({ format: 'turtle', prefixes: { ex: 'http://example.org/', foaf: 'http://xmlns.com/foaf/0.1/' } }); // N-Quads output const nQuadsWriter = new StreamWriter({ format: 'n-quads' }); ``` -------------------------------- ### N3Store Constructor Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md The Store constructor accepts an optional options object for configuration. ```javascript new Store(quads, options) ``` -------------------------------- ### Instantiate N3Parser Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-parser.md Create a new N3Parser instance. You can provide a configuration object to customize its behavior, such as setting the base IRI, document format, or RDF factory. ```javascript const { Parser } = require('n3'); // Basic parser const parser = new Parser(); // Parser with configuration const turtleParser = new Parser({ baseIRI: 'http://example.org/', format: 'turtle', }); const n3Parser = new Parser({ baseIRI: 'http://example.org/rules', format: 'n3', explicitQuantifiers: true, }); ``` -------------------------------- ### End N3 Writer and Get Output Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-writer.md Finalizes the writing process and closes the output stream. For string-based writers, a callback receives the generated output. For stream-based writers, it signals completion. ```javascript // String-based writer const stringWriter = new Writer(); stringWriter.addPrefix('ex', 'http://example.org/'); stringWriter.addQuad( DataFactory.namedNode('http://example.org/alice'), DataFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), DataFactory.namedNode('http://example.org/Person') ); stringWriter.end((error, output) => { if (error) console.error('Error:', error); else console.log('Output:\n', output); }); // Stream-based writer const fs = require('fs'); const writer = new Writer(fs.createWriteStream('data.ttl')); writer.addQuad(...); writer.end(() => console.log('File written')); ``` -------------------------------- ### Reasoning with N3.js Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/quick-reference.md Set up and perform reasoning using N3.js. This involves parsing N3 data, extracting rules, and applying a reasoner. ```javascript const { Reasoner, Parser, Store, getRulesFromDataset } = require('n3'); const parser = new Parser({ format: 'n3' }); const store = new Store(parser.parse(n3String)); // Extract rules from N3 dataset const rules = getRulesFromDataset(store); // Apply reasoning const reasoner = new Reasoner(store); reasoner.reason(rules); // Or provide rules directly const customRules = [{ premise: [quad(var('x'), type, parent)], conclusion: [quad(var('x'), type, ancestor)] }]; reasoner.reason(customRules); ``` -------------------------------- ### Resolve Relative IRI using BaseIRI Instance Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md An instance of BaseIRI can be used to resolve relative IRIs against its configured base IRI. This example shows converting a full IRI to its relative form. ```javascript const { BaseIRI } = require('n3'); console.log(BaseIRI.supports('http://example.org/')); // true console.log(BaseIRI.supports('http://example.org/data/')); // true console.log(BaseIRI.supports('file:///path/to/file')); // false console.log(BaseIRI.supports('urn:example:test')); // false const base = new BaseIRI('http://example.org/data/'); const relative = base.toRelative('http://example.org/data/item'); console.log(relative); // 'item' ``` -------------------------------- ### Query and Export RDF Data Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/module-structure.md Use this pattern to query quads from an N3 Store based on a subject and then export them using the Writer. Prefixes can be configured for the output. The writer's 'end' method is used to get the final serialized string. ```javascript const { Writer } = require('n3'); const writer = new Writer({ prefixes: { ex: 'http://example.org/' } }); store.getQuads(subject, null, null).forEach(quad => { writer.addQuad(quad); }); writer.end((err, result) => { console.log(result); }); ``` -------------------------------- ### Initialize N3EntityIndex with Options Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Instantiate N3EntityIndex with custom options. This is useful for optimizing memory usage when multiple stores share the same entity index. ```javascript new N3EntityIndex(options) ``` -------------------------------- ### Query Triples with Store.match() Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/README.md Use the `match` method on a Store instance to query for triples. Any parameter can be a wildcard (null/undefined). ```javascript store.match(subject, predicate, object, graph) ``` -------------------------------- ### Execute Callback for Each Quad Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Use forEach to execute a callback function for every quad that matches the specified pattern. The callback receives the quad and the dataset it belongs to. ```javascript store.forEach(callback, subject, predicate, object, graph); ``` ```javascript store.forEach(quad => { console.log(`${quad.subject.value} ${quad.predicate.value} ${quad.object.value}`); }); ``` -------------------------------- ### Create RDF Quads using DataFactory Source: https://github.com/rdfjs/n3.js/blob/main/README.md Demonstrates how to create RDF quads using the DataFactory, including named nodes, literals, and default graphs. This follows the RDF.js low-level specification. ```javascript const { DataFactory } = N3; const { namedNode, literal, defaultGraph, quad } = DataFactory; const myQuad = quad( namedNode('https://ruben.verborgh.org/profile/#me'), // Subject namedNode('http://xmlns.com/foaf/0.1/givenName'), // Predicate literal('Ruben', 'en'), // Object defaultGraph(), // Graph ); console.log(myQuad.termType); // Quad console.log(myQuad.value); // '' console.log(myQuad.subject.value); // https://ruben.verborgh.org/profile/#me console.log(myQuad.object.value); // Ruben console.log(myQuad.object.datatype.value); // http://www.w3.org/1999/02/22-rdf-syntax-ns#langString console.log(myQuad.object.language); // en ``` -------------------------------- ### RDF Reasoning with N3.js Source: https://github.com/rdfjs/n3.js/blob/main/README.md Applies reasoning rules to an RDF store. Ensure rules are parsed into a Dataset and the store is initialized. ```JavaScript import { Reasoner, Store, Parser } from 'n3'; const parser = new Parser({ format: 'text/n3' }); const rules = ` { ?s a ?o . ?o ?o2 . } => { ?s a ?o2 . } . ` const rulesDataset = new Store(parser.parse(rules)); const dataset = new Store(/* Dataset */) // Applies the rules to the store; mutating it const reasoner = new Reasoner(store); reasoner.reason(rulesDataset); ``` -------------------------------- ### Import N3 Util Functions Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-util.md Import all utility functions from the n3 library. This is typically done once at the beginning of your script. ```javascript const { isNamedNode, isBlankNode, isLiteral, isVariable, isQuad, isDefaultGraph, prefix, prefixes } = require('n3').Util; ``` -------------------------------- ### Convert and Process with Store Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-streaming.md Reads a Turtle file, loads its quads into a Store, then writes them back to a file in Turtle format, allowing for sorting and deduplication. ```javascript const fs = require('fs'); const { StreamParser, StreamWriter, Store } = require('n3'); const parser = new StreamParser(); const store = new Store(); const writer = new StreamWriter({ format: 'turtle' }); // Read from file, load into store, and write back with sorting/deduplication fs.createReadStream('input.ttl') .pipe(parser) .on('data', quad => store.addQuad(quad)) .on('end', () => { store.getQuads().forEach(quad => writer.addQuad(quad)); writer.end(); }); writer.pipe(fs.createWriteStream('output.ttl')); ``` -------------------------------- ### Load Turtle File into Store Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/quick-reference.md Reads a Turtle file from the filesystem, parses it into N3 quads, and adds them to an N3 Store. Ensure 'data.ttl' exists in the same directory. ```javascript const { Parser, Store } = require('n3'); const fs = require('fs'); const store = new Store(); const text = fs.readFileSync('data.ttl', 'utf-8'); const parser = new Parser(); const quads = parser.parse(text); store.addQuads(quads); console.log(`Loaded ${store.size} quads`); ``` -------------------------------- ### Writer Configuration Options Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/quick-reference.md Configure the N3.js writer with options for format, prefixes, and base IRI. ```javascript new Writer(stream, { format: 'turtle', // or 'trig', 'n-triples', 'n-quads' prefixes: { ex: '...' }, baseIRI: 'http://example.org/' }) ``` -------------------------------- ### Prefix Functions Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/quick-reference.md Create and use prefix functions for concise RDF term creation. Supports both single prefix creation and a prefix registry. ```javascript const { Util } = require('n3'); // Create prefix function const ex = Util.prefix('http://example.org/'); const person = ex('Person'); // namedNode('http://example.org/Person') // Create prefix registry const p = Util.prefixes({ '': 'http://example.org/', ex: 'http://example.org/ns/', foaf: 'http://xmlns.com/foaf/0.1/' }); const term = p('ex')('Person'); // namedNode('http://example.org/ns/Person') ``` -------------------------------- ### forEach Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-store.md Executes a callback function on all quads that match the provided pattern. The callback receives the quad and the dataset as arguments. ```APIDOC ## forEach(callback, subject, predicate, object, graph) ### Description Executes a callback function on all quads that match the provided pattern. The callback receives the quad and the dataset as arguments. ### Method `forEach` ### Parameters #### Callback Function - **callback** (function) - Required - Called with `(quad, dataset)` for each quad #### Pattern Matching (Optional) - **subject** (Term) - Optional - Subject to match - **predicate** (Term) - Optional - Predicate to match - **object** (Term) - Optional - Object to match - **graph** (Term) - Optional - Graph to match ### Example ```javascript store.forEach(quad => { console.log(`${quad.subject.value} ${quad.predicate.value} ${quad.object.value}`); }); ``` ``` -------------------------------- ### Pipe Parser Directly to Store Import Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-streaming.md An alternative method to import parsed quads directly into a Store by piping the parser output to the store's import method. ```javascript const parser = new StreamParser(); const store = new Store(); fs.createReadStream('data.ttl') .pipe(parser) .pipe(store.import(parser)); parser.on('end', () => { console.log('All quads imported'); }); ``` -------------------------------- ### Format Conversion using Streams Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/module-structure.md This pattern demonstrates converting RDF data from one format to another using streams. It pipes data from an input file stream through a StreamParser and then a StreamWriter to an output file stream. The formats can be specified in the options. ```javascript const { StreamParser, StreamWriter } = require('n3'); const fs = require('fs'); fs.createReadStream('input.ttl') .pipe(new StreamParser({ format: 'turtle' })) .pipe(new StreamWriter({ format: 'n-quads' })) .pipe(fs.createWriteStream('output.nq')); ``` -------------------------------- ### N3Parser Constructor Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-parser.md Initializes a new N3Parser instance with optional configuration. The parser can handle different RDF formats and resolve relative IRIs using a base IRI. ```APIDOC ## Constructor ### Description Initializes a new N3Parser instance with optional configuration. ### Method `new Parser(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Optional - Configuration object. - **options.baseIRI** (string) - Optional - Base IRI for resolving relative IRIs. - **options.format** (string) - Optional - Document format: 'turtle', 'trig', 'n-triples', 'n-quads', 'n3'. Defaults to 'turtle'. - **options.factory** (object) - Optional - RDF.js factory for creating terms and quads. Defaults to N3DataFactory. - **options.blankNodePrefix** (string) - Optional - Prefix for auto-generated blank nodes. - **options.lexer** (object) - Optional - Custom lexer instance. - **options.explicitQuantifiers** (boolean) - Optional - Enable explicit quantifier parsing in N3. Defaults to false. - **options.parseUnsupportedVersions** (boolean) - Optional - Allow parsing unsupported RDF versions. Defaults to false. - **options.version** (string) - Optional - Expected RDF version. - **options.isImpliedBy** (boolean) - Optional - Support log:isImpliedBy predicate. Defaults to false. ### Request Example ```javascript const { Parser } = require('n3'); // Basic parser const parser = new Parser(); // Parser with configuration const turtleParser = new Parser({ baseIRI: 'http://example.org/', format: 'turtle', }); const n3Parser = new Parser({ baseIRI: 'http://example.org/rules', format: 'n3', explicitQuantifiers: true, }); ``` ### Response None (constructor) ### Error Handling None explicitly documented for constructor. ``` -------------------------------- ### Handle Prefix Events Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-streaming.md Listen for 'prefix' events emitted by imported streams to ensure prefixes are included in the output if the format supports them. ```javascript writer.on('prefix', (prefix, iri) => { // Prefix will be included in output (if format supports it) }); ``` -------------------------------- ### RDF Reasoning with N3.js Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/module-structure.md This pattern shows how to perform reasoning on RDF data. It involves parsing N3 data, extracting rules, creating a Reasoner instance with the store, and then calling the reason method. The store is updated with derived facts after reasoning. ```javascript const { Parser, Store, Reasoner, getRulesFromDataset } = require('n3'); const parser = new Parser({ format: 'n3' }); const store = new Store(parser.parse(n3String)); const rules = getRulesFromDataset(store); const reasoner = new Reasoner(store); reasoner.reason(rules); // store now contains derived facts ``` -------------------------------- ### Instantiate N3EntityIndex Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-util.md Import and create a new instance of the EntityIndex class. This is for advanced use cases and requires importing the class directly. ```javascript const { EntityIndex } = require('n3'); const index = new EntityIndex(); ``` -------------------------------- ### Configure Custom N3.js Lexer Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/configuration.md Instantiate a custom lexer with specific options and pass it to the N3.js Parser. Use this to enable N3-specific syntax or line-mode. ```javascript const customLexer = new N3Lexer({ lineMode: false, n3: true, isImpliedBy: false }); const parser = new Parser({ lexer: customLexer }); ``` -------------------------------- ### prefixes(defaultPrefixes, factory) Source: https://github.com/rdfjs/n3.js/blob/main/_autodocs/api-reference-util.md Creates a function that registers and expands namespace prefixes. This function simplifies the process of defining and using multiple prefixes. ```APIDOC ## prefixes(defaultPrefixes, factory) ### Description Creates a function that registers and expands namespace prefixes. This function simplifies the process of defining and using multiple prefixes. ### Method N/A (JavaScript function) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters - **defaultPrefixes** (object) - Optional - Initial prefix mapping; keys are labels, values are IRIs (Defaults to {}) - **factory** (object) - Optional - RDF.js factory for creating terms (Defaults to N3DataFactory) ### Returns `function` - Function for registering and accessing prefixes ### Usage The returned function accepts a prefix label: - If called with an IRI string: registers a new prefix - If called with no arguments: retrieves the registered prefix function ### Example ```javascript const { Util, DataFactory } = require('n3'); // Initialize with default prefixes const prefixFn = Util.prefixes({ '': 'http://example.org/', // Default prefix ex: 'http://example.org/ns/', foaf: 'http://xmlns.com/foaf/0.1/' }); // Use existing prefixes const person = prefixFn('ex')('Person'); console.log(person.value); // 'http://example.org/ns/Person' const name = prefixFn('foaf')('name'); console.log(name.value); // 'http://xmlns.com/foaf/0.1/name' // Register new prefix prefixFn('schema', 'http://schema.org/'); const thing = prefixFn('schema')('Thing'); console.log(thing.value); // 'http://schema.org/Thing' // Access default prefix (empty label) const resource = prefixFn('')('resource'); console.log(resource.value); // 'http://example.org/resource' // Error handling try { prefixFn('unknown')('item'); } catch (e) { console.log(e.message); // 'Unknown prefix: unknown' } ``` ### Practical Example - Building Queries: ```javascript const { Parser, Store, Util } = require('n3'); // Create prefix functions const p = Util.prefixes({ rdf: 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', rdfs: 'http://www.w3.org/2000/01/rdf-schema#', ex: 'http://example.org/' }); const store = new Store(); // Query using prefixes const rdfType = p('rdf')('type'); const person = p('ex')('Person'); const name = p('ex')('name'); const people = store.getSubjects(rdfType, person); people.forEach(subject => { const names = store.getObjects(subject, name); names.forEach(n => console.log(n.value)); }); ``` ``` -------------------------------- ### Create Blank Nodes and Lists with N3.Writer Source: https://github.com/rdfjs/n3.js/blob/main/README.md Manually create blank nodes and lists using `writer.blank()` and `writer.list()` when using streaming writers to ensure correct Turtle/TriG syntax. ```JavaScript const writer = new N3.Writer({ prefixes: { c: 'http://example.org/cartoons#', foaf: 'http://xmlns.com/foaf/0.1/' } }); writer.addQuad( writer.blank( namedNode('http://xmlns.com/foaf/0.1/givenName'), literal('Tom', 'en')), namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), namedNode('http://example.org/cartoons#Cat') ); writer.addQuad(quad( namedNode('http://example.org/cartoons#Jerry'), namedNode('http://xmlns.com/foaf/0.1/knows'), writer.blank([{ predicate: namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), object: namedNode('http://example.org/cartoons#Cat'), },{ predicate: namedNode('http://xmlns.com/foaf/0.1/givenName'), object: literal('Tom', 'en'), }]) )); writer.addQuad( namedNode('http://example.org/cartoons#Mammy'), namedNode('http://example.org/cartoons#hasPets'), writer.list([ namedNode('http://example.org/cartoons#Tom'), namedNode('http://example.org/cartoons#Jerry'), ]) ); writer.end((error, result) => console.log(result)); ```