-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver
executable file
·97 lines (85 loc) · 2.57 KB
/
server
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env node
var express = require('express'),
fs = require("fs"),
n3 = require('n3'),
owl2html = require('./lib/owl2html.js');
/**
* Configuration
*/
var config = JSON.parse(fs.readFileSync('config.json', 'utf8'));
if (!config.files) {
console.error("Please check your config file. It should contain turtle files");
process.exit();
}
var files = config.files;
/*****************************************************************************/
var server = express();
/**
* Get all triples
*/
function getTriples(file, callback){
var turtleStream = fs.createReadStream(file, 'utf8');
var parser = n3.StreamParser();
var triples = [];
turtleStream.pipe(parser);
parser.on("data", function (triple) {
triples.push(triple);
}).on("end", function () {
callback(triples);
});
}
server.use("/ns/assets",express.static(process.cwd() + '/public'));
server.get('/ns/', function (req,res) {
var fullURL = req.protocol + "://" + req.get('host') + req.url + "/";
var links = [];
for (var key in files) {
links.push(fullURL + key);
}
res.send(links);
});
/**
* Respond with all triples
*/
server.get('/ns/:name/?', function (req, res) {
var name = req.route.params.name;
//check if name exists on the directory
fs.exists(name, function(exists) {
if (!exists) {
//handle file through nodejs
if (typeof files[name] !== 'undefined') {
var file = files[name];
var format = req.accepts('text/html','text/turtle','application/json');
if ( format === "text/html" ) {
getTriples(file, function(triples){
res.send(owl2html(triples));
});
} else if ( format === "text/turtle" ) {
var turtleStream = fs.createReadStream(file, 'utf8');
res.download(file, name + ".ttl");
} else if ( format === "application/json" ) {
getTriples(file, function(triples){
res.send(triples);
});
} else {
res.status(406).send("Not acceptable. We do accept: text/html, text/turtle and application/json");
}
} else {
res.status(404).send("Nothing here");
}
} else {
//handle file through file instead
res.download(name);
}
});
});
/**
* Quick fix for deeper URIs - this should be smarter though...
*/
server.get('/ns/:name/*',function (req, res) {
var name = req.route.params.name;
var url = req.protocol + "://" + req.get('host') + "/ns/" + name;
res.redirect(303,url);
});
server.listen(8080, function() {
console.log('Server listening at http://localhost:8080');
});