Home > Web Front-end > JS Tutorial > body text

Node.js implements batch removal of BOM file headers

PHPz
Release: 2018-09-30 09:56:00
forward
1479 people have browsed it

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);
Copy after login

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

Related labels:
source:jb51.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template