-
-
Save scopevale/b068168b76d30001dd4a4ff38d77b85c to your computer and use it in GitHub Desktop.
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
function getImportsFromFile(fileName) { | |
const readline = require('readline'); | |
const fs = require('fs'); | |
const imports = []; | |
return new Promise((resolve, reject) => { | |
const readStream = fs.createReadStream(fileName); | |
readStream.on('error', (err) => reject(err)); | |
const rl = readline.createInterface({input: readStream}); | |
rl.on('line', (line) => { | |
if (line.indexOf('import') > -1) { | |
const importFileName = line.match(/'(.*?)'/); | |
if (importFileName) { | |
imports.push(importFileName[1]); | |
} | |
} | |
}); | |
rl.on('close', () => { | |
resolve(imports); | |
}) | |
}); | |
} | |
async function getAllDependencies(initialFileName) { | |
const orderedDependencies = []; | |
const workerQueue = [initialFileName]; | |
try { | |
while (workerQueue.length) { | |
const currentFile = workerQueue.shift(); | |
if (orderedDependencies.indexOf(currentFile) === -1) { | |
orderedDependencies.unshift(currentFile); | |
} | |
workerQueue.push(...await getImportsFromFile(currentFile)); | |
} | |
} catch (err) { | |
throw err; | |
} | |
return orderedDependencies; | |
} | |
const cliFileName = process.argv[2]; | |
getAllDependencies(cliFileName) | |
.then((result) => console.log(result)) | |
.catch((err) => console.log(`Derp${err}`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good example of Promise based read file line by line