Skip to content

Instantly share code, notes, and snippets.

@Kuniwak
Created June 22, 2013 15:56
Show Gist options
  • Save Kuniwak/5841369 to your computer and use it in GitHub Desktop.
Save Kuniwak/5841369 to your computer and use it in GitHub Desktop.
Promiseパターンを使ったファイル処理のテスト。 引数の受け渡しと取り扱いが見えにくいのはPromiseパターンの欠点かな。
var fs = require('fs');
var path = require('path');
var promise = require('node-promise');
var fsp = require('node-promise/fs-promise');
const TEXT_DIR_PATH = path.resolve(__dirname, 'texts');
const OUTPUT_FILE_PATH = path.resolve(__dirname, 'output.txt');
var texts = [];
var textDirPaths = [
path.resolve(TEXT_DIR_PATH, '1'),
path.resolve(TEXT_DIR_PATH, '2'),
path.resolve(TEXT_DIR_PATH, '3'),
path.resolve(TEXT_DIR_PATH, '4')
];
var filePaths = [];
promise.all(textDirPaths.map(function(textDirPath) {
var alltxtp = new promise.Promise();
return fsp.readdir(textDirPath).then(function(fileNames) {
var txtpArr = [];
fileNames.forEach(function(fileName) {
if (fileName.match(/\.txt$/)) {
var filePath = path.join(textDirPath, fileName);
var txtp = fsp.readFile(filePath);
txtpArr.push(txtp);
}
});
return promise.all(txtpArr);
}).then(function(txts) {
return txts.join('');
});
})).then(function(txts) {
fs.writeFile(OUTPUT_FILE_PATH, txts.join('\n\n\n'));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment