Home  >  Article  >  Web Front-end  >  Node.js implements batch removal of BOM file headers

Node.js implements batch removal of BOM file headers

PHPz
PHPzforward
2016-05-16 16:25:241480browse

This article mainly introduces Node.js to implement batch removal of BOM file headers. This article directly gives the implementation code. Friends in need can refer to it.

A former colleague wrote a tool, but there was a bug. After replacing the file, the format of the original file changed to utf8 BOM. This kind of XML with BOM may not be read under Mac, so I You need to write a tool to handle it.

In fact, the idea is relatively simple. First traverse the directory, then read the directory, remove the first three bytes of the file, and then save it as a file in UTF-8 format. Just enter the code:)

var fs = require('fs');
var path = "目标路径..";


function readDirectory(dirPath) {
    if (fs.existsSync(dirPath)) {
        var files = fs.readdirSync(dirPath);
        
        files.forEach(function(file) {
            var filePath = dirPath + "/" + file;
            var stats = fs.statSync(filePath);
            if (stats.isDirectory()) {
                console.log('\n读取目录: ', filePath, "\n");
                readDirectory(filePath);
            } else if (stats.isFile()) {
                var buff = fs.readFileSync(filePath);
                if (buff[0].toString(16).toLowerCase() == "ef" && buff[1].toString(16).toLowerCase() == "bb" && buff[2].toString(16).toLowerCase() == "bf") {
                    //EF BB BF 239 187 191
                    console.log('\发现BOM文件:', filePath, "\n");
                    buff = buff.slice(3);
                    fs.writeFile(filePath, buff.toString(), "utf8");
                }
            }
        });       
    } else {
        console.log('Not Found Path : ', dirPath);
    }
}
readDirectory(path);

The above is the entire content of this chapter. For more related tutorials, please visit Node.js Video Tutorial!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete