From cb0e5769492591646bde7c8a7e05b483ea2ce07d Mon Sep 17 00:00:00 2001 From: Corey Johnson Date: Tue, 1 May 2012 14:07:05 -0700 Subject: [PATCH] Add fs.extension --- spec/stdlib/fs-spec.coffee | 8 ++++++++ src/stdlib/fs.coffee | 11 +++++++++++ 2 files changed, 19 insertions(+) diff --git a/spec/stdlib/fs-spec.coffee b/spec/stdlib/fs-spec.coffee index 4d56330d7..11ef89c83 100644 --- a/spec/stdlib/fs-spec.coffee +++ b/spec/stdlib/fs-spec.coffee @@ -18,6 +18,14 @@ describe "fs", -> expect(fs.join('/a/b/', 'c', 'd')).toBe '/a/b/c/d' expect(fs.join('a', 'b/c/', 'd/')).toBe 'a/b/c/d/' + describe ".extension(path)", -> + it "returns the extension of a file", -> + expect(fs.extension("a/b/corey.txt")).toBe '.txt' + expect(fs.extension("a/b/corey.txt.coffee")).toBe '.coffee' + + it "returns an empty string for paths without an extension", -> + expect(fs.extension("a/b.not-extension/a-dir")).toBe '' + describe ".async", -> directoryPath = null beforeEach -> diff --git a/src/stdlib/fs.coffee b/src/stdlib/fs.coffee index 1e0a9be80..968cbfa6a 100644 --- a/src/stdlib/fs.coffee +++ b/src/stdlib/fs.coffee @@ -27,6 +27,17 @@ module.exports = exists: (path) -> $native.exists path + # Returns the extension of a file. The extension of a file is the + # last dot (excluding any number of initial dots) followed by one or + # more non-dot characters. Returns an empty string if no valid + # extension exists. + extension: (path) -> + match = @base(path).match(/\.[^\.]+$/) + if match + match[0] + else + "" + join: (paths...) -> return paths[0] if paths.length == 1 [first, rest...] = paths