Node.js to realize bulk removal of BOM file header _node.js

Source: Internet
Author: User

Previous colleagues wrote a tool, but there is a bug, is the original file after the replacement file format into a utf8 BOM, this with the BOM XML under the Mac may not read out, so you need to write a tool to deal with.

In fact, the idea is relatively simple, first traverse the directory, and then read the directory, the first three bytes of the file to remove, and then save the file in utf-8 format, directly on the code bar:)

Copy Code code as follows:



var fs = require (' FS ');


var path = "Target 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 ' read directory: \ n ', FilePath , "\ n");
                Readdirectory ( FilePath);
           } else if (Stats.isfile ()) {
                 var buff = Fs.readfilesync (filePath );
                if (buff[0). ToString. toLowerCase () = = "EF" && buff[1].tostring. toLowerCase () = = "BB" && buff[2].tostring ( toLowerCase () = = "BF") {
                    //ef BB BF 239 187 191
  &Nbsp;                 Console.log (' \ Discovery BOM file: ', FilePath, ' \ n ');

Buff = Buff.slice (3);
Fs.writefile (FilePath, buff.tostring (), "UTF8");
}
}
});

} else {
Console.log (' Not Found Path: ', Dirpath);
}
}

Readdirectory (path);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.