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 );