11const cheerio = require ( 'cheerio' )
22const fetch = require ( 'node-fetch' )
3-
43const toJson = require ( './utils/tojson' )
54
65const defaultOptions = {
@@ -11,33 +10,36 @@ const defaultOptions = {
1110}
1211
1312const htmlTableToJson = async ( options = defaultOptions , headers ) => {
14- const { url, html, selector, format } = { ...defaultOptions , ...options }
15-
16- let data
17-
18- if ( url ) {
19- const response = await fetch ( url )
20- data = await response . text ( )
21- } else if ( html ) {
22- data = html
23- } else {
24- return [ ]
25- }
26-
27- const $ = cheerio . load ( data )
28-
29- if ( $ ( 'table' ) . html ( ) === null ) {
30- throw new Error (
31- `Please provide ${ url ? 'url' : 'html' } which contains table`
32- )
33- }
34-
35- let body = toJson ( $ , selector , headers )
36-
37- if ( format === 'json' ) {
38- return JSON . stringify ( body )
39- } else {
40- return body
13+ try {
14+ const { url, html, selector, format } = { ...defaultOptions , ...options }
15+
16+ let data
17+
18+ if ( url ) {
19+ const response = await fetch ( url )
20+ data = await response . text ( )
21+ } else if ( html ) {
22+ data = html
23+ } else {
24+ return [ ]
25+ }
26+
27+ const $ = cheerio . load ( data )
28+
29+ if ( $ ( 'table' ) . html ( ) === null ) {
30+ throw new Error (
31+ `Please provide ${ url ? 'url' : 'html' } which contains table`
32+ )
33+ }
34+
35+ let body = toJson ( $ , selector , headers )
36+ if ( format === 'json' ) {
37+ return JSON . stringify ( body )
38+ } else {
39+ return body
40+ }
41+ } catch ( e ) {
42+ throw new Error ( e )
4143 }
4244}
4345
0 commit comments