copy-bom.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // Avoid Buffer constructor on newer versions of Node.js
  9. var _buff = (Buffer.alloc ? Buffer.alloc(BUF_LENGTH) : (new Buffer(BUF_LENGTH)));
  10. function copyFolderWithBom(src, dest) {
  11. var stats = fs.lstatSync(src);
  12. var destFolder = path.dirname(dest);
  13. var destFolderExists = fs.existsSync(destFolder);
  14. var performCopy = false;
  15. if (stats.isFile()) {
  16. if (!destFolderExists) {
  17. fs.mkdirSync(destFolder);
  18. }
  19. if (src.match(/\.(css|less)$/)) {
  20. copyFileAddingBomSync(src, dest);
  21. } else {
  22. copyFileSync(src, dest);
  23. }
  24. }
  25. else if (stats.isDirectory()) {
  26. if (!fs.existsSync(destFolder)) {
  27. fs.mkdirSync(destFolder);
  28. }
  29. if (!fs.existsSync(dest)) {
  30. fs.mkdirSync(dest);
  31. }
  32. fs.readdirSync(src).forEach(function(d) {
  33. if (d !== 'bom') {
  34. copyFolderWithBom(path.join(src, d), path.join(dest, d));
  35. }
  36. });
  37. }
  38. }
  39. function copyFileAddingBomSync(srcFile, destFile) {
  40. var contents = fs.readFileSync(srcFile, { encoding: 'utf8' });
  41. if (!contents.length || contents.charCodeAt(0) !== 0xFEFF) {
  42. contents = '\ufeff' + contents;
  43. }
  44. fs.writeFileSync(destFile, contents, { encoding: 'utf8' });
  45. }
  46. function copyFileSync(srcFile, destFile) {
  47. var fdr = fs.openSync(srcFile, 'r');
  48. var stat = fs.fstatSync(fdr);
  49. var fdw = fs.openSync(destFile, 'w', stat.mode);
  50. var bytesRead = 1;
  51. var pos = 0;
  52. while (bytesRead > 0) {
  53. bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
  54. fs.writeSync(fdw, _buff, 0, bytesRead);
  55. pos += bytesRead;
  56. }
  57. fs.closeSync(fdr);
  58. fs.closeSync(fdw);
  59. }
  60. return {
  61. copyFolderWithBom: copyFolderWithBom
  62. };
  63. };