Node. js notes (10) Nodejs and DOM operations, node. jsnodejs
As a back-end language, Nodejs directly performs DOM operations against the separation principle.
However, if it is a small personal website, it is no harm if it is a little more flexible.
Here we will introduce the cheerio plug-in, which is implemented based on jquery and slightly streamlined to provide nodejs with dom operations like jquery.
Ps:Originally, jsdom is also an option, but unfortunately the latest version of jsdom no longer supports nodejs
The following is an example:
// This example reads the file name from filelist.txtand returns it to function getFileList () {var content = fs under the select tag with the listselect class in index.html. readFileSync ('. /index.html '); $ = cheerio. load (content); $ ('select. listselect '). empty (); // avoid duplication. Clear all sub-tags lineReader under the tag before loading. eachLine ('. /filelist.txt ', function (line, last) {// lineReader is a nodejs plug-in for reading files by line. You can install var file = line on your own. substr (line. lastIndexOf ('') + 1); $ ('select. listselect '). append ('<option class = "listoption" value =' + file + '>' + file + '</option>'); if (last) {fs. writeFile (". /index.html ", developer.html (), function (err) {if (err) throw err; console. log ("Saved") ;}); return false ;}});
Why?
$ = cheerio.load(content);
This writing method is really tangled. It must be the $ symbol or it will lead to errors. I personally understand that it seems to be consistent with the selector in jquery and it is specially written like this.
For more operations, see
Https://npmjs.org/package/cheerio
Official documents or the following translation documents
Https://cnodejs.org/topic/5203a71844e76d216a727d2e
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.