Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add path.parse #3

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
27 changes: 27 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,33 @@ exports.extname = function(path) {
return splitPath(path)[3];
};

exports.parse = function(pathString) {
assertPath(pathString);

var allParts = splitPath(pathString);
if (!allParts || allParts.length !== 4) {
throw new TypeError("Invalid path '" + pathString + "'");
}
allParts[1] = allParts[1] || '';
allParts[2] = allParts[2] || '';
allParts[3] = allParts[3] || '';

return {
root: allParts[0],
dir: allParts[0] + allParts[1].slice(0, allParts[1].length - 1),
base: allParts[2],
ext: allParts[3],
name: allParts[2].slice(0, allParts[2].length - allParts[3].length)
};
};

function assertPath(path) {
if (typeof path !== 'string') {
throw new TypeError('Path must be a string. Received ' +
util.inspect(path));
}
}

function filter (xs, f) {
if (xs.filter) return xs.filter(f);
var res = [];
Expand Down
22 changes: 22 additions & 0 deletions test/test-path.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
var path = require('../index')
var test = require('tape').test

test('parse works on file', function(t) {
var output = path.parse('test-path.js');
t.equal(output.root, '', 'root is correct');
t.equal(output.dir, '', 'dir is correct');
t.equal(output.base, 'test-path.js', 'base is correct');
t.equal(output.ext, '.js', 'ext is correct');
t.equal(output.name, 'test-path', 'name is correct');
t.end();
})

test('parse works on file with path', function(t) {
var output = path.parse('/home/test/test-path.js');
t.equal(output.root, '/', 'root is correct');
t.equal(output.dir, '/home/test', 'dir is correct');
t.equal(output.base, 'test-path.js', 'base is correct');
t.equal(output.ext, '.js', 'ext is correct');
t.equal(output.name, 'test-path', 'name is correct');
t.end();
})