2
\$\begingroup\$

I've written the following code to get all .txt files in a directory and read+delete them, repeating every 15 seconds.

var fs = require("fs");
var path = require("path");
var Q = require("q");
var dir = "stuff";

var analyseFile = function(fileData, callback) { ... }; // Not important.

var deleteFile = function(filePath, callback) { ... }; // Not important.

var processStuffDir = function() {
  Q.nfcall(fs.readdir, dir).then(function(files) {
    return Q.all(
      files.filter(function(file) { 
        return path.extname(file) === ".txt";
      }).map(function(file) {
        var filePath = path.join(dir, file);
        return Q.nfcall(fs.readFile, filePath).then(function(data) {
          return Q.nfcall(analyseFile, data.toString());
        }).then(function() {
          return Q.nfcall(deleteFile, filePath);
        });
      })
    );
  }).then(function() {
    setTimeout(processStuffDir, 15000);
  });
};

processStuffDir();

This works, but it's my first foray into using promises. So my question is, can this be re-written in a simpler/more succinct manner? More chaining of promises would be nice, if possible.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Looks fine, apart from the fact that any self-written functions (analyseFile, deleteFile) should return promises right away instead of taking callbacks. \$\endgroup\$ – Bergi Jun 24 '14 at 18:46
2
\$\begingroup\$

This is Bluebird, but it's very similar to Q in syntax. Note the automatic promisification and utility methods:

var Promise= require("bluebird");
var fs = Promise.promisify(require("fs"));
var path = require("path");

var dir = "stuff";

var analyseFile = function(fileData, callback) { ... }; // Not important.

var deleteFile = function(filePath, callback) { ... }; // Not important.

var fileOps = {
    analyse: Promise.promisify(analyseFile), // do this _once_
    delete: Promise.promisify(deleteFile)
}

var processStuffDir = function() {
  return fs.readDirAsync(dir).filter(function(files) {
        return path.extname(file) === ".txt";
  }).map(function(file){
        return path.join(dir, file)
  }).map(function(file) {
      return fs.readFileAsync(file).then(function(data) {
          return fileOps.analyse(data.toString());
      }).then(function() {
          return fileOps.delete(filePath);
      });
  }).delay(15000).then(processStuffDir);
};

processStuffDir();
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.