UNPKG

mu.js

Version:

µ is the new $

57 lines (47 loc) 1.53 kB
'use strict' /* µ.js */ const fs = require('fs') const cp = require('child_process') const path = require('path') const request = require('request') const cheerio = require('cheerio').load const md5 = require('md5') const base64 = require('./b64') const jQuery = (string, options) => new Promise((deliver, fail) => { try { deliver( cheerio(string, options) ) } catch (reason) { fail(reason) } }) const visit = (url, options, req = { /* */ }) => new Promise((deliver, fail) => { const opt = { url } for (let option in req) opt[option] = req[option] request(opt, (problem, response, body) => { if (problem) fail(problem) jQuery(body, options).then(jq => { jq.response = response deliver(jq) }).catch(fail) }) }) const µ = (url, options) => visit(url, options) µ.fromFile = (path, options) => new Promise((deliver, fail) => { fs.readFile(path, (problem, buffer) => { if (problem) fail(problem) jQuery(buffer.toString(), options).then(deliver).catch(fail) }) }) µ.fromFileSync = (path, options) => cheerio( fs.readFileSync(path).toString(), options ) µ.fromString = (string, options) => cheerio(string, options) µ.sync = url => cheerio( cp.execSync(`node ${path.join(__dirname, 'sync.js')} "${url}" "${base64.encode(JSON.stringify({}))}"`).toString().trim() ) module.exports = µ