fsio.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /**
  2. * This has to be required *after* using Bluebird's promisifyAll() on fs
  3. */
  4. var fs = require('fs');
  5. var path = require('path');
  6. var Promise = require('bluebird');
  7. if(typeof fs.readdirAsync !== 'function') {
  8. // console.error("scandirAsync module requires promisifying fs with Bluebird's Promise.promisifyAll()");
  9. Promise.promisifyAll(fs);
  10. }
  11. function scandirAsync(path, excludes) {
  12. excludes = excludes || [];
  13. return fs.readdirAsync(path)
  14. .then(dirContent => {
  15. excludes.forEach(file => {
  16. var idxInContent = dirContent.indexOf(file);
  17. if(idxInContent !== -1) {
  18. dirContent.splice(idxInContent, 1);
  19. }
  20. });
  21. return dirContent;
  22. });
  23. }
  24. function readFileAsync(file) {
  25. return fs.readFileAsync(file)
  26. .then(buf => (buf.toString()));
  27. }
  28. function readFilesAsync(fullPath, files) {
  29. // console.log('reading files', files, 'from path', path);
  30. return Promise.reduce(files,
  31. (carry, f) => readFileAsync(fullPath + '/' + f)
  32. .then(content =>
  33. (carry.concat([{
  34. type: path.extname(f).substr(1),
  35. name: f,
  36. content
  37. }]))
  38. ),
  39. []
  40. );
  41. }
  42. module.exports = {
  43. scandirAsync,
  44. readFileAsync,
  45. readFilesAsync
  46. };