Created
February 15, 2014 18:06
-
-
Save riston/9022931 to your computer and use it in GitHub Desktop.
Split files lines into array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Q = require('q'), | |
fs = require('fs'); | |
Q.longStackSupport = true; | |
var filterLargeFilename = function (array) { | |
var length = 10; | |
return array.filter(function (name) { | |
return (name.length <= length); | |
}); | |
}; | |
var isFile = function (path) { | |
return Q.nfcall(fs.stat, path) | |
.then(function (stat) { | |
return { | |
file: stat.isFile(), | |
path: path | |
}; | |
}, function (error) { | |
return {}; | |
}); | |
}; | |
var filterFiles = function (result) { | |
return result.filter(function (current) { | |
return current.file ? current : false; | |
}); | |
}; | |
var read = function (path) { | |
return Q.nfcall(fs.readFile, path, 'utf-8'); | |
}; | |
var splitFilesByLines = function (fileArray) { | |
return fileArray.map(function (file) { | |
return file.split('\n'); | |
}); | |
}; | |
// The code executions starts here, | |
// 1. read current directory all files and directories | |
// 2. filter long file names, currently longer than 10 characters | |
// 3. check which of the result are files | |
// 4. Read the each file content | |
// 5. Split the file content by lines | |
// 6. Print the results | |
Q.nfcall(fs.readdir, '.') | |
.then(filterLargeFilename) | |
.then(function (result) { | |
// Create the promise array of only files | |
var promises = result.map(isFile); | |
return Q.all(promises); | |
}) | |
.then(filterFiles) | |
.then(function (result) { | |
var filesContent = []; | |
result.forEach(function (file) { | |
filesContent.push(read(file.path)); | |
}); | |
return Q.all(filesContent); | |
}) | |
.then(splitFilesByLines) | |
.then(function (result) { | |
console.log(result); | |
}) | |
.fail(function (error) { | |
console.log("Something went wrong ", error); | |
}) | |
.done(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment