Node. js removes BOM headers in batches and node. js removes bom

Source: Internet
Author: User

Node. js removes BOM headers in batches and node. js removes bom

My colleagues wrote a tool, but there is a bug that after the file is replaced, the format of the original file is changed to utf8 BOM. XML with BOM may not be readable on Mac, therefore, you need to write a tool for processing.

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 the file as a UTF-8 file. Go directly to the Code :)

Copy codeThe Code is 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 (16 ). toLowerCase () = "ef" & buff [1]. toString (16 ). toLowerCase () = "bb" & buff [2]. toString (16 ). toLowerCase () = "bf "){
// Ef bb bf 239 187 191
Console. log ('\ found BOM file:', filePath, "\ n ");

Buff = buff. slice (3 );
Fs. writeFile (filePath, buff. toString (), "utf8 ");
}
}
});

} Else {
Console. log ('not Found Path: ', dirPath );
}
}

ReadDirectory (path );

Related Article

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.