[英]Read and modify HTML from a local file with JavaScript
I can't think of an elegant solution. 我想不出一个优雅的解决方案。 But, what would be the best way to process an HTML file, modify it and save it back using a script on the command line? 但是,处理HTML文件,对其进行修改并在命令行上使用脚本将其保存回去的最佳方法是什么? I want to basically run this script, proving the HTML file as an argument, add a data-test=<randomID>
into every <div>
element, and save it back into the file. 我想基本运行此脚本,证明HTML文件作为参数,将data-test=<randomID>
到每个<div>
元素中,然后将其保存回文件中。 I was thinking I could write a JavaScript script to execute with node
but am not sure how I would get the contents of the provided file, or what to store the content as. 我当时想我可以编写一个JavaScript脚本来与node
一起执行,但不确定如何获取所提供文件的内容,或将内容存储为什么。 Thanks for any pointers. 感谢您的指导。
Solved with jsdom
(thanks for the tip, user1600124): 使用jsdom
解决(感谢提示,user1600124):
var jsdom = require("jsdom"),
fs = require('fs');
if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME');
process.exit(1);
}
var file = process.argv[2];
fs.readFile(file, 'utf8', function(err, data) {
if (err) throw err;
jsdom.env(
data,
["http://code.jquery.com/jquery.js"],
function (errors, window) {
var $ = window.jQuery;
$("p, li").each(function(){
$(this).attr("data-test", "test");
});
$(".jsdom").remove();
console.log( window.document.doctype + window.document.innerHTML );
var output = window.document.doctype + window.document.innerHTML;
fs.writeFile(file, output, function(err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.