Skip to content

Commit dc53b8c

Browse files
authored
Merge pull request #6 from davorpa/bugfix/5
[BUGFIX-5] Improve file media type extraction from directory name
2 parents 4a38a8f + c91ac28 commit dc53b8c

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

index.js

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -215,13 +215,21 @@ function getFilesFromDir(dir) {
215215

216216
/**
217217
* Retrieves the folder name from a string representing a directory and file
218-
* @param {String} dir A string representing a directory in the format "./directory/file"
218+
* @param {String} str - A string representing a path directory alike in the format "./directory/file"
219219
* @returns {String} The extracted directory name
220220
*/
221-
function getMediaFromDirectory(dir) {
222-
const slash = dir.lastIndexOf("/");
223-
let mediaType = dir.slice(2, slash);
224-
return mediaType;
221+
function getMediaTypeFromDirectoryPath(str) {
222+
str = path.resolve(str); // sanatize and expand (OS independent)
223+
let type;
224+
if (fs.lstatSync(str).isDirectory()) {
225+
// if path is itself a directory, use it name as result
226+
type = path.basename(str);
227+
} else {
228+
// if not... parent/previous slug is always a directory; extract this part
229+
// path.sep: Windows -> "\", Unix -> "/"
230+
type = str.split(path.sep).slice(-2, -1).join(path.sep);
231+
}
232+
return type;
225233
}
226234

227235
/**
@@ -315,7 +323,7 @@ function parseDirectory(directory) {
315323
let dirChildren = []; // this will hold the output each markdown doc
316324
let dirErrors = []; //contains error for a given directory
317325

318-
let mediaType = getMediaFromDirectory(directory);
326+
let mediaType = getMediaTypeFromDirectoryPath(directory);
319327
const filenames = getFilesFromDir(path.resolve(directory));
320328
filenames.forEach((filename) => {
321329
const doc = fs.readFileSync(filename);

0 commit comments

Comments
 (0)