fsio.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. }
  10. function scandirAsync(path, excludes) {
  11. excludes = excludes || [];
  12. return fs.readdirAsync(path)
  13. .then(dirContent => {
  14. excludes.forEach(file => {
  15. var idxInContent = dirContent.indexOf(file);
  16. if(idxInContent !== -1) {
  17. dirContent.splice(idxInContent, 1);
  18. }
  19. });
  20. return dirContent;
  21. });
  22. }
  23. function readFileAsync(file) {
  24. return fs.readFileAsync(file)
  25. .then(buf => (buf.toString()));
  26. }
  27. function readFilesAsync(fullPath, files) {
  28. // console.log('reading files', files, 'from path', path);
  29. return Promise.reduce(files,
  30. (carry, f) => readFileAsync(fullPath + '/' + f)
  31. .then(content =>
  32. (carry.concat([{
  33. type: path.extname(f).substr(1),
  34. name: f,
  35. content
  36. }]))
  37. ),
  38. []
  39. );
  40. }
  41. module.exports = {
  42. scandirAsync,
  43. readFileAsync,
  44. readFilesAsync
  45. };