forked from weo-edu/express-robots
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
45 lines (39 loc) · 1.21 KB
/
index.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
const fs = require('fs');
const asArray = (value = []) => Array.isArray(value) ? value : [value];
module.exports = function(robots, {express = require('express')} = {}) {
const app = express.Router();
if(robots) {
robots = 'string' === typeof robots
? fs.readFileSync(robots, 'utf8')
: render(robots);
} else
robots = '';
app.get('/robots.txt', function(req, res) {
res.header('Content-Type', 'text/plain');
res.send(robots);
});
return app;
};
function render(robots) {
return asArray(robots).map(function(robot) {
let userAgentArray = [];
if (Array.isArray(robot.UserAgent)) {
userAgentArray = robot.UserAgent.map(function(userAgent) {
return 'User-agent: ' + userAgent
});
} else {
userAgentArray.push('User-agent: ' + robot.UserAgent);
}
if (robot.CrawlDelay) {
userAgentArray.push('Crawl-delay: ' + robot.CrawlDelay);
}
return userAgentArray.concat(asArray(robot.Disallow).map(function(disallow) {
if (Array.isArray(disallow)) {
return disallow.map(function(line) {
return 'Disallow: ' + line;
}).join('\n');
}
return 'Disallow: ' + disallow;
})).join('\n');
}).join('\n');
}