Skip to content

Instantly share code, notes, and snippets.

@jiyuujin
Last active April 4, 2020 08:39
Show Gist options
  • Save jiyuujin/b6b7a28b018ac8fc0bac75cf80b571b2 to your computer and use it in GitHub Desktop.
Save jiyuujin/b6b7a28b018ac8fc0bac75cf80b571b2 to your computer and use it in GitHub Desktop.
メタ情報を取得する
'use strict'
import { getMetaInfo }from './ogp'
const marked = require('marked')
const async = require('async')
// https://github.com/markedjs/marked/issues/1279
const linkSupport = /^!?\[((?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|[^\[\]\\])*?)\]\(\s*(<(?:\\[<>]?|[^\s<>\\])*>|(?:\\[()]?|\([^\s\x00-\x1f()\\]*\)|[^\s\x00-\x1f()\\])*?(?:\s+=(?:[\w%]+)?x(?:[\w%]+)?)?)(?:\s+("(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)))?\s*\)/;
module.exports = async function markdownLinkViewer(markdown, opt = {}, callback) {
let links = []
const renderer = new marked.Renderer()
marked.InlineLexer.rules.normal.link = linkSupport
marked.InlineLexer.rules.gfm.link = linkSupport
marked.InlineLexer.rules.breaks.link = linkSupport
renderer.link = function (href, title, text) {
links.push(href)
}
renderer.image = function (href, title, text) {
href = href.replace(/ =\d*%?x\d*%?$/, "")
links.push(href)
}
marked(markdown, {
renderer: renderer
})
let ogpValues = []
for (let link of links) {
const { defaults } = await getMetaInfo(link)
ogpValues.push(defaults)
const props = ['title', 'description']
for (let prop of props) {
console.log(`og ${prop}: `)
console.log(defaults[prop])
console.log('-----')
}
}
async.map(ogpValues, function(ogpValue, callback) {
callback(null, ogpValue)
}, callback)
}
/**
* メタ情報を取得する
* @param {*} url URL
*/
export const getMetaInfo = async (url) => {
const jsdom = require('jsdom')
const { JSDOM } = jsdom
const virtualConsole = new jsdom.VirtualConsole()
let defaults = {}
try {
const dom = await JSDOM.fromURL(url, {
virtualConsole
})
const doc = dom.window.document
// const metaEl = doc.getElementsByTagName('meta')
const titleEl = doc.getElementsByTagName('title')
const description = doc.querySelector('meta[name=\'description\']')
if (titleEl.length) {
defaults.title = titleEl[0].textContent || ''
}
if (description) {
defaults.description = description.content || ''
}
return { defaults }
} catch(err) {
throw err
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment