I want to add a code snippet to an html file using the node fs command line tool. I saw this solution how to append to a file on particular position using node.js? but it uses the position for appending to a file.
I have this html snippet
<html><body><h1>hello world</body></html>
I want to append
<script>console.log('hello world')</script>
before the closing body tag. I want the output to be like this
<html><body><h1>hello world</h1><script>console.log('hello world')</script></body></html>
Why not use Regex?
fs = require('fs')
fs.readFile('./test.html', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var toPrepand = "<script>console.log('hello world')</script>";
data = data.replace(/\<\/body>/g, toPrepand + '</body>');
console.log(data);
});
You won't have to think about where to place - because you already say - right before the </body>
tag.
After that simply write the new data to that HTML file.
If you also want to know how to write your file directly afterward:
var fs = require('fs')
fs.readFile('./test.html', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
var toPrepand = "<script>console.log('hello world')</script>";
var result = data.replace(/\<\/body>/g, toPrepand + '</body>');
fs.writeFile('./test.html', result, 'utf8', function (err) {
if (err) return console.log(err);
});
});
There are many options to do so - find the position or use a HTML parser or simply string replace that string.
You can use simple string operations to achieve this:
var initialString = '<html><body><h1>hello world</body></html>';
var insert = '<script>console.log("hello world")</script>';
then find the position using indexOf:
var pos = initialString.indexOf('</body>');
slice and concat the strings:
var output = [initialString.slice(0, pos), insert, initialString.slice(pos)].join('')
And use output of course :-)
If you want something more scalable you could also have a look at any HTML parser / virtual DOM implementation for Node (like jsdom https://github.com/tmpvar/jsdom )
I would like to use the 'cheerio' node package to do it. https://github.com/cheeriojs/cheerio
that is really useful and just like using jQuery.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.