Modify the HTML file name automatically generated Hexo

REVIEW

When we generate a static blog use Hexo framework, in fact, is the output of your written .md files into HTML files for rendering, which is the HTML file name .md file name.

For convenience we edit the article, in order to pass the filename to know that this is what articles are usually named after the .md file into Chinese and even the title of the article, then when generating HTML file is the file name of the Chinese.

For example: 钢铁是怎么炼成的.mdAfter hexo gthe command is generated 钢铁是怎么炼成的.html; execute hexo dthe command file will be pushed to your warehouse, so when you visit this chapter, corresponding to the address bar is http://xxxx/.../钢铁是怎么炼成的.html, so it looks very awkward, not search engine friendly.

So how do we modify the names of the letters with numbers HTML it? Today we'll explore it. View results

(1) modify the naming policy when generating HTML

We from Hexo是基于Node.js的,Hexo生成HTML文件this sentence to inspire, Hexo folder will definitely get all the .md file generates an HTML file, naming format xxx.md -> xxx.html, then certainly creates a directory for HTML files.

This time we want to, we can not be in the Hexo generates an HTML file, modify the HTML naming strategy, is about to change our original naming custom of naming?

With the idea went ahead. So each file to Hexo's go, it's where the converted file. When I found several files, I gave up too many documents, too difficult to find, no different from needle in a haystack. Looking for a long time did not find the hexo module. . .

image.png

(2) modify the HTML file name

Since that method just does not work, then we open a new path, after Hexo generates an HTML file, go to modify the file name.
JS how to get all the files in the directory it? Search, I can say Node.js, just Hexo is based on the Node.js.
So (except hexo directory) to create rename.js following documents, which the new file name in any directory can define their own generation strategy.

//引入fs操作文件
var fs = require('fs');
//引入jquery
var join = require('path').join;
var jsdom = require('jsdom');
const {JSDOM} = jsdom;
const {document} = (new JSDOM('<!doctype html><html><body></body></html>')).window;
global.document = document;
global.window = document.defaultView;
global.jQuery = require('jquery')(window);
const $ = require('jquery')(window);

var eng = ['a','b','c','d','e','f','g','h','i','j'];
//生成随机6位数字字母 全路径新文件名
function getNewNameRandom(_file){
    var fiveInt = Math.floor(Math.random()*89999+10000);//无五位随机数
    var eng_index = Math.floor(Math.random()*10+1);//一位字母
    return _file.substr(0,_file.lastIndexOf('\\')+1) + eng[eng_index-1] + fiveInt + ".html";//新文件名,全路径
}
function getAllFiles(jsonPath){
    let jsonFiles = [];
    function findJsonFile(path){
        let files = fs.readdirSync(path);
        files.forEach(function (item, index) {
            let fPath = join(path,item);
            let stat = fs.statSync(fPath);
            if(stat.isDirectory() === true) {
                findJsonFile(fPath);
            }
            if (stat.isFile() === true) { 
              jsonFiles.push(fPath);
            }
        });
    }
    findJsonFile(jsonPath);
    console.log(jsonFiles);//指定目录下的文件,包括子目录
    return jsonFiles;
}
function doFileRename(){
    var jsonFiles = getAllFiles("F:/static/page");//生成的HTML文件
    for(var i=0;i<jsonFiles.length;i++){
        var _file = jsonFiles[i];
        var newName = getNewNameRandom(_file);//新文件名,全路径
        console.log(newName)
        fs.rename(_file,newName,function(err){//重命名
            if(err){
                console.log("重命名失败");
            }else{
                console.log("重命名成功");
            }
        })
    }
}
doFileRename();

Then open a command line in the directory where the JS executionnode rename.js

image.png

看日志,是全部成功了,找到对应目录,真的成功了。

image.png

存在的问题

hexo g时,又会生成原来的那样中文命名的HTML,我们重命名的还在(执行hexo clean就不在了),这不是我们想要的,或许你会说,再执行一次node rename.js,这不是我想要的,因为,这样每次执行,原来的Html的名字都会变,我不知道这会不会影响SEO,即使不会也不想这样,因为假如别人收藏了你的文章链接,但你的文章HTML名字变了,那别人收藏的就无效了啊。

所以这种方式会存在这个最严重的问题。

(3)Base64生成文件名

修改JS代码

//引入fs操作文件
var fs = require('fs');
//引入jquery
var join = require('path').join;
var jsdom = require('jsdom');
const {JSDOM} = jsdom;
const {document} = (new JSDOM('<!doctype html><html><body></body></html>')).window;
global.document = document;
global.window = document.defaultView;
global.jQuery = require('jquery')(window);
const $ = require('jquery')(window);

var eng = ['a','b','c','d','e','f','g','h','i','j'];
//文件名Base64后 根据算法从编码中取6位作为新文件名
function getNewNameBase64(_file){
    var fileName = _file.substr(_file.lastIndexOf('\\')+1,_file.length);//文件名
    var fi_bs64 = Buffer.from(fileName.substr(0,fileName.lastIndexOf('.'))).toString('base64')//转成base64编码
    var arr = fi_bs64.split("");
    var len = arr.length;
    var fis = "";
    for(var i=1;i<=6;i++){
        var s1 = arr[Math.floor(len/(2*i))];
        if(s1=='/'||s1=='+'){
            var eng_index = Math.floor(Math.random()*10+1);
            s1 = eng[eng_index-1];
        }
        fis = fis + s1;
    }
    console.log(fis)
    return _file.substr(0,_file.lastIndexOf('\\')+1) + fis + ".html";
}
function getAllFiles(jsonPath){
    let jsonFiles = [];
    function findJsonFile(path){
        let files = fs.readdirSync(path);
        files.forEach(function (item, index) {
            let fPath = join(path,item);
            let stat = fs.statSync(fPath);
            if(stat.isDirectory() === true) {
                findJsonFile(fPath);
            }
            if (stat.isFile() === true) { 
              jsonFiles.push(fPath);
            }
        });
    }
    findJsonFile(jsonPath);
    console.log(jsonFiles);//指定目录下的文件,包括子目录
    return jsonFiles;
}
function doFileRename(){
    var jsonFiles = getAllFiles("F:/static/page");//生成的HTML文件
    for(var i=0;i<jsonFiles.length;i++){
        var _file = jsonFiles[i];
        var newName = getNewNameBase64(_file);//新文件名,全路径
        console.log(newName)
        fs.rename(_file,newName,function(err){//重命名
            if(err){
                console.log("重命名失败");
            }else{
                console.log("重命名成功");
            }
        })
    }
}
doFileRename();

效果

image.png

看日志,是全部成功了。找到对应目录,看下真的成功了。

存在的问题

这种方法解决了上面那个方法存在的问题,即每次执行node rename.js只要原文件名不变,生成的新文件名不变。但是需要限制文件名不能变,否则新文件名还是会变。还有一点是不能重复执行node rename.js,因为会根据新的再次生成新的。

小结

第2、3种方式都需要注意的是,
1、新名字的生成规则,要保证唯一性,不能重复
2、每次hexo g之后hexo d之前,要执行node rename.js
3、不要重复执行
4、第2种不太可行,推荐第3种

(4)修改文件生成规则

以上两种方式都需要我们来写代码,而且要手动执行node rename.js
对于这么懒的我来说很不方便,有没有更好的办法?答案是肯定的。

我们可以找到Hexo的根配置文件_config.yml,打开它,找到下图这个

image.png

我把他改成这样了,page是目录,执行hexo g会在public下生成,我让生成的HTML文件都放在page下,:fileName.html是HTML的命名格式,其中fileName是个变量。这个变量从哪来?

Your .md file, as shown below, in your article head increase this variable and assign a value, which is the file name when generating HTML, and other files attention is not repeated
image.png

In other words, as long as the head of each article you add this property, and the assignment and ensure that the only OK, not as troublesome as the above two methods that.

In this execution hexo gbecame so after the
image.png

Execution hexo dvisit my site after that is the case

image.png

To avoid forget to write fileName property at the time of writing, we can modify the template, there are three templates directory under the scaffolds
to add fileName attribute template

image.png

Problems

The need to manually write the name of the file, and to ensure unique, but more convenient

to sum up

Recommend using the third and fourth, the third major is the solution generated after each execution hexo g HTML file name unchanged (provided that the .md file name unchanged), but do not forget to run node rename.js; fourth as long as they have their own naming convention like, for example: today is may m, the date of 29, Wednesday w, time is 17:00, the file name can be is m29w17.

If you know HTML generated in Hexo when you can change the file name or there is other good way, you can leave a message to tell me, thank you.


This article and methods provided herein are original authors, their own way out, please indicate the source, thanks! ! !

Guess you like

Origin www.cnblogs.com/ibigboy/p/10968037.html