Merge pull request #6 from davorpa/bugfix/5

[BUGFIX-5] Improve file media type extraction from directory name
pull/12/head
Eric Hellman 2022-09-14 13:55:21 -04:00 committed by GitHub
commit dc53b8c803
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 14 additions and 6 deletions

View File

@ -215,13 +215,21 @@ function getFilesFromDir(dir) {
/** /**
* Retrieves the folder name from a string representing a directory and file * Retrieves the folder name from a string representing a directory and file
* @param {String} dir A string representing a directory in the format "./directory/file" * @param {String} str - A string representing a path directory alike in the format "./directory/file"
* @returns {String} The extracted directory name * @returns {String} The extracted directory name
*/ */
function getMediaFromDirectory(dir) { function getMediaTypeFromDirectoryPath(str) {
const slash = dir.lastIndexOf("/"); str = path.resolve(str); // sanatize and expand (OS independent)
let mediaType = dir.slice(2, slash); let type;
return mediaType; if (fs.lstatSync(str).isDirectory()) {
// if path is itself a directory, use it name as result
type = path.basename(str);
} else {
// if not... parent/previous slug is always a directory; extract this part
// path.sep: Windows -> "\", Unix -> "/"
type = str.split(path.sep).slice(-2, -1).join(path.sep);
}
return type;
} }
/** /**
@ -315,7 +323,7 @@ function parseDirectory(directory) {
let dirChildren = []; // this will hold the output each markdown doc let dirChildren = []; // this will hold the output each markdown doc
let dirErrors = []; //contains error for a given directory let dirErrors = []; //contains error for a given directory
let mediaType = getMediaFromDirectory(directory); let mediaType = getMediaTypeFromDirectoryPath(directory);
const filenames = getFilesFromDir(path.resolve(directory)); const filenames = getFilesFromDir(path.resolve(directory));
filenames.forEach((filename) => { filenames.forEach((filename) => {
const doc = fs.readFileSync(filename); const doc = fs.readFileSync(filename);