index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. var path = require('path');
  3. var fs = require('graceful-fs');
  4. var stripBom = require('strip-bom');
  5. var stripBomStream = require('strip-bom-stream');
  6. var File = require('vinyl');
  7. var pify = require('pify');
  8. var Promise = require('pinkie-promise');
  9. var fsP = pify(fs, Promise);
  10. exports.read = function (pth, opts) {
  11. opts = opts || {};
  12. var cwd = opts.cwd || process.cwd();
  13. var base = opts.base || cwd;
  14. pth = path.resolve(cwd, pth);
  15. return fsP.stat(pth).then(function (stat) {
  16. var file = new File({
  17. cwd: cwd,
  18. base: base,
  19. path: pth,
  20. stat: stat
  21. });
  22. if (opts.read === false) {
  23. return file;
  24. }
  25. if (opts.buffer === false) {
  26. file.contents = fs.createReadStream(pth).pipe(stripBomStream());
  27. return file;
  28. }
  29. return fsP.readFile(pth).then(function (contents) {
  30. file.contents = stripBom(contents);
  31. return file;
  32. });
  33. });
  34. };
  35. exports.readSync = function (pth, opts) {
  36. opts = opts || {};
  37. var cwd = opts.cwd || process.cwd();
  38. var base = opts.base || cwd;
  39. pth = path.resolve(cwd, pth);
  40. var contents;
  41. if (opts.read !== false) {
  42. contents = opts.buffer === false ?
  43. fs.createReadStream(pth).pipe(stripBomStream()) :
  44. stripBom(fs.readFileSync(pth));
  45. }
  46. return new File({
  47. cwd: cwd,
  48. base: base,
  49. path: pth,
  50. stat: fs.statSync(pth),
  51. contents: contents
  52. });
  53. };