-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
124 lines (82 loc) · 3.15 KB
/
app.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const cheerio = require('cheerio');
const ejs = require('ejs');
const fs = require('fs');
const writeStream = fs.createWriteStream('posts.csv');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static('public'));
app.set('view engine', 'ejs');
let pageText;
let paraText;
app.get('/', function(req, res){
res.render('generate');
})
app.get('/generate', function(req, res){
res.render('generate');
});
app.post('/generate', function(req, res){
let url = req.body.url; // get url from form
let selection = req.body.selection;
pageText = [];
paraText = [];
//process data on html page
request(url, function (error, response, body) {
if(!error && response.statusCode === 200){
const $ = cheerio.load(body); //load the html page into Cheerio
if (selection === 'getSentences'){ //Get Sentences from Blog Posts
let regex = /["']?[A-Z][^.?!]+((?![.?!]['"]?\s["']?[A-Z][^.?!]).)+[.?!'"]+/g;
const paragraphs = $('p');
paragraphs.each(function(index, element){
const sentence = $(this).text();
if (sentence.match(regex)){
if (sentence.startsWith('<')){
pageText.slice(index, 1);
} else {
pageText.push(sentence.trim());
}
}
});
pageText.forEach(function(sentence){
writeStream.write(`${sentence}\n`);
});
res.redirect('/sentences');
} else if (selection === 'getParagraphs'){ //Get Paragraphs from Blog Posts
//let regex = /["']?[A-Z][^.?!]+((?![.?!]['"]?\s["']?[A-Z][^.?!]).)+[.?!'"]+/g;
const paragraphs = $('p');
paragraphs.each(function(index, element){
const sentence = $(this).text();
if (sentence.startsWith('<')){
paraText.slice(index, 1);
} else {
paraText.push(sentence.trim());
}
});
paraText.forEach(function(sentence){
writeStream.write(`${sentence}|\n`);
});
res.redirect('/paragraphs');
} else {
console.log(error);
res.redirect('/');
}// end else-if statement
} //end if request error handling
}); // end request
}); //end app.post
app.get('/sentences', function(req, res){
res.render('results-sentences', {paragraphs: pageText});
});
app.get('/paragraphs', function(req, res){
res.render('results-paragraphs', {paragraphs: paraText});
});
app.get('/download', function(req, res){
res.download(__dirname + '/posts.csv');
});
app.get('/import-guide', function(req, res){
res.render('import-guide');
})
app.listen(process.env.PORT || 3000, function(){
console.log('Server started on port 3000.');
})