copy-bom.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*jshint latedef: nofunc */
  2. // This is used to copy a folder (the test/less/* files & sub-folders), adding a BOM to the start of each LESS and CSS file.
  3. // This is a based on the copySync method from fs-extra (https://github.com/jprichardson/node-fs-extra/).
  4. module.exports = function() {
  5. var path = require('path'),
  6. fs = require('fs');
  7. var BUF_LENGTH = 64 * 1024;
  8. var _buff = new Buffer(BUF_LENGTH);
  9. function copyFolderWithBom(src, dest) {
  10. var stats = fs.lstatSync(src);
  11. var destFolder = path.dirname(dest);
  12. var destFolderExists = fs.existsSync(destFolder);
  13. var performCopy = false;
  14. if (stats.isFile()) {
  15. if (!destFolderExists) {
  16. fs.mkdirSync(destFolder);
  17. }
  18. if (src.match(/\.(css|less)$/)) {
  19. copyFileAddingBomSync(src, dest);
  20. } else {
  21. copyFileSync(src, dest);
  22. }
  23. }
  24. else if (stats.isDirectory()) {
  25. if (!fs.existsSync(destFolder)) {
  26. fs.mkdirSync(destFolder);
  27. }
  28. if (!fs.existsSync(dest)) {
  29. fs.mkdirSync(dest);
  30. }
  31. fs.readdirSync(src).forEach(function(d) {
  32. if (d !== 'bom') {
  33. copyFolderWithBom(path.join(src, d), path.join(dest, d));
  34. }
  35. });
  36. }
  37. }
  38. function copyFileAddingBomSync(srcFile, destFile) {
  39. var contents = fs.readFileSync(srcFile, { encoding: 'utf8' });
  40. if (!contents.length || contents.charCodeAt(0) !== 0xFEFF) {
  41. contents = '\ufeff' + contents;
  42. }
  43. fs.writeFileSync(destFile, contents, { encoding: 'utf8' });
  44. }
  45. function copyFileSync(srcFile, destFile) {
  46. var fdr = fs.openSync(srcFile, 'r');
  47. var stat = fs.fstatSync(fdr);
  48. var fdw = fs.openSync(destFile, 'w', stat.mode);
  49. var bytesRead = 1;
  50. var pos = 0;
  51. while (bytesRead > 0) {
  52. bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
  53. fs.writeSync(fdw, _buff, 0, bytesRead);
  54. pos += bytesRead;
  55. }
  56. fs.closeSync(fdr);
  57. fs.closeSync(fdw);
  58. }
  59. return {
  60. copyFolderWithBom: copyFolderWithBom
  61. };
  62. };