How to use iFramely as a Node library

How to use iFramely as a Node library

iFramely is a service that can be used to extract data from web pages from meta tags, opengraph tags, twitter cards, and to generate oEmbeds when possible.

I've put some examples of the same below.

Screen-Shot-2019-01-30-at-3.09.34-PM

Sunrise In The Office by Karim Nafatni | 500px.com

iFramely provides this functionality in a subscription service online, which I'd recommend checking out here. However, most of the code powering iFramely also happens to be open source with the source code available on GitHub.

However, out of the box, the library is only usable via an HTTP based API. You might want to use the library directly like any other Node library though, because maybe the HTTP request overhead is not acceptable to you, or you don't want to bother with running another server. Here's what you can do in that case:

First install the library via npm:

npm install --save iframely

Then download the iframely whitelist from their site, and save it in the folder where you place the following code as iframely-whitelist.json.

Then create a file and name it something like runIframely.js, and put the following code inside it:

const _ = require("lodash");
const mkdirp = require("mkdirp");
const fs = require("fs-extra");

const MACOS_CHROME_USERAGENT =
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3669.0 Safari/537.36";

const iframelyConfig = {
    // Disable logging to iframely server
    WHITELIST_LOG_URL: null,

    CACHE_ENGINE: 'no-cache',

    USER_AGENT: MACOS_CHROME_USERAGENT,
    WHITELIST_DIR: "whitelist"
};

// Monkey-patch the config object
global.CONFIG = _.extend({}, require('iframely/config'), iframelyConfig);
wl = require("iframely/lib/whitelist");

// Load iframely whitelist offline
mkdirp.sync("node_modules/iframely/whitelist");

fs.copySync("iframely-whitelist.json", "node_modules/iframely/whitelist/iframely-whitelist.json",
    { overwrite: false } );

const iframely = require("iframely");

module.exports = iframelyRunner = function (url) {
    return new Promise((resolve, reject) => {
        iframely.run(url, { v: 1.3, getWhitelistRecord: wl.findWhitelistRecordFor }, function (err, res) {
           if (err) reject(err);
           resolve(res);
        });
    });
};

And now when you want to use the library, you can use it like this:

const runIframely = require("./runIframely.js");

runIframely("http://gizmodo.com/the-fermi-paradox-where-the-hell-are-the-other-earths-1580345495").then(function (res) {
    // do something with response
}).catch(function () {
    // do something with error
});

And there you have it!