Skip to content

Commit

Permalink
fix get caller bug
Browse files Browse the repository at this point in the history
  • Loading branch information
victorteokw committed Apr 22, 2019
1 parent 01a5e36 commit 8c402ad
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 2 deletions.
6 changes: 4 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
const path = require('path');
const fs = require('fs');
const getCallerFilename = require('./lib/getCallerFilename');
const matchExt = require('./lib/matchExt');
const loaders = require('./lib/loaders');

const loadIt = (location) => {
const callerFile = getCallerFilename();
const requirerDirectory =
module.parent.filename ?
path.dirname(module.parent.filename) :
path.resolve(callerFile) === callerFile ?
path.dirname(callerFile) :
process.cwd();
let finalPath = path.resolve(requirerDirectory, location);
if (path.extname(finalPath) === '') {
Expand Down
18 changes: 18 additions & 0 deletions lib/getCallerFilename.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function getCallerFilename() {
const originalFunc = Error.prepareStackTrace;
let callerfile;
try {
const err = new Error();
Error.prepareStackTrace = function (err, stack) { return stack; };
const currentfile = err.stack.shift().getFileName();
while (err.stack.length) {
err.stack.shift();
callerfile = err.stack.shift().getFileName();
if(currentfile !== callerfile) break;
}
} catch (e) {}
Error.prepareStackTrace = originalFunc;
return callerfile;
}

module.exports = getCallerFilename;
3 changes: 3 additions & 0 deletions tests/filename-resolving/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"behavior": true
}
24 changes: 24 additions & 0 deletions tests/filename-resolving/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const assert = require('assert');
const loadIt = require('../../index');

describe('Resolve filename: ', function() {

it('relative with . (a dot)', function() {
assert.deepEqual(
loadIt('./config.json'),
{
'behavior': true
}
);
});

it('relative with .. (two dots)', function() {
assert.deepEqual(
loadIt('../imhere.json'),
{
'iam': 'here'
}
);
});

});
3 changes: 3 additions & 0 deletions tests/imhere.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"iam": "here"
}

0 comments on commit 8c402ad

Please sign in to comment.