Skip to content

Instantly share code, notes, and snippets.

@dfreedm
Created April 8, 2015 19:27
Show Gist options
  • Save dfreedm/dfc442589a9bd934070b to your computer and use it in GitHub Desktop.
Save dfreedm/dfc442589a9bd934070b to your computer and use it in GitHub Desktop.
Example of removing <head> and <body> with dom5
#!/usr/bin/env node
/**
* @license
* Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
// jshint node: true
'use strict';
var fs = require('fs');
var dom5 = require('dom5');
var pred = dom5.predicates;
var headMatcher = pred.hasTagName('head');
var bodyMatcher = pred.hasTagName('body');
var docText = '';
process.stdin.setEncoding('utf-8');
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
docText += chunk;
}
});
process.stdin.on('end', function() {
var doc = dom5.parse(docText);
var head = dom5.query(doc, headMatcher);
var body = dom5.query(doc, bodyMatcher);
var html = head.parentNode;
dom5.remove(head);
dom5.remove(body);
var reparent = function(node) {
node.parentNode = html;
};
var headNodes = head.childNodes;
var bodyNodes = body.childNodes;
headNodes.forEach(reparent);
bodyNodes.forEach(reparent);
html.childNodes = headNodes.concat(bodyNodes);
process.stdout.write(dom5.serialize(doc));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment