diff --git a/index.js b/index.js index 4a7009c..c0a6d3f 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,10 @@ +const http = require('http'); const https = require('https'); +const { URL } = require('url'); module.exports = { command: 'appify ', + getTitle, // exported for testing register: (command, modules) => { command .option('-t,--title [title]') @@ -27,22 +30,36 @@ module.exports = { function getTitle(url) { - const TITLE_REGEX = /(.*)<\/title>/im; - - return new Promise((resolve, reject)=>{ - https.get(url, (res) => { - let body = '', title = ''; - res.on('data', (chunk) => { - body += chunk; - if(!title && TITLE_REGEX.test(body)) { - title = body.match(TITLE_REGEX)[1]; + const TITLE_REGEX = /<title>(.*)<\/title>/im; + + let protocol; + try { + const parsed = new URL(url); + if (parsed.protocol === 'https:') { + protocol = https; + } else if (parsed.protocol === 'http:') { + protocol = http; + } else { + return Promise.reject(new Error(`Unsupported protocol: ${parsed.protocol}. Only http: and https: are supported.`)); } - }); - res.on('end', () => { - resolve(title); - }); - }).on('error', (err) => { - reject(''); + } catch (e) { + return Promise.reject(new Error('Invalid URL')); + } + + return new Promise((resolve, reject) => { + protocol.get(url, (res) => { + let body = '', title = ''; + res.on('data', (chunk) => { + body += chunk; + if (!title && TITLE_REGEX.test(body)) { + title = body.match(TITLE_REGEX)[1]; + } + }); + res.on('end', () => { + resolve(title); + }); + }).on('error', (err) => { + reject(err); + }); }); - }) } \ No newline at end of file diff --git a/package.json b/package.json index 2442bc3..2bd8d23 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,8 @@ "description": "Convert any SPA to a lightweight desktop app - Appify plugin for Neutralinojs CLI", "main": "index.js", "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "test": "echo \"Error: no test specified\" && exit 1", + "test:getTitle": "node scripts/test-getTitle.js" }, "repository": { "type": "git",