Skip to content

Instantly share code, notes, and snippets.

@toanalien
Created June 4, 2015 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toanalien/5361da404088dd1809e1 to your computer and use it in GitHub Desktop.
Save toanalien/5361da404088dd1809e1 to your computer and use it in GitHub Desktop.
Manipulating file paths
/**
* Normalizing paths
* you can use the normalize function present in the path module to normalize path, string, thus taking care of .., ., and //.
*/
var path = require('path');
path.normalize('/foo/bar//baz/asdf/quux/..');
// => '/foo/bar/baz/asdf'
/**
* Joining paths
* by using path.join(), you can concatenate path strings.
*/
var path = require('path');
path.join('/foo', 'bar', 'bax/asdf', 'quux', '..');
// => '/foo/bar/baz/asdf'
/**
* Resolving paths
* you can resolve a series of paths into a normalized absolute path by path.resolve().
* it does not tap into the underlying filesystem to try to see if the path exists; it simply manipulates path.
*/
var path = require('path');
path.resolve('/foo/bar', './baz');
// => /foo/bar/baz
path.resolve('/foo/bar', '/tmp/file/');
// => /tmp/file
// if the resulting path is not absolute, path.resolve will prepend the current working directory to the path
path.resolve('wwwroot', 'static_files/png', '../gif/image.gif');
// if currently in /home/myself/node, it returns
// => /home/myself/node/wwwroot/static_files/gif/image.gif
/**
* Finding the relative path between two absolute paths
*/
var path = require('path');
path.relative('/data/orandea/test/aaa', 'data/orandea/impl/bbb');
// => ../../impl/bbb
/**
* Extracting components of path
*/
var path = require('path');
path.dirname('foo/bar/baz/asdf/quux.txt');
// => /foo/bar/baz/asdf
path.basename('/foo/bar/bax/asdf/quux.txt');
// => quux.txt
// you can subtract the file extension from the result by passing in an optional second argument with the expected extension
path.basename('/foo/bar/bax/asdf/quux.txt', '.txt');
// => quux
//you can determine the extension by using path.extname() like so
path.extname('/a/b/index.html');
// => '.html'
path.extname('a/b.c/index');
// => ''
path.extname('a/b.c/d.');
// => '.'
/**
* Determining the existence of a path
*/
path.exists('/etc/passwd', function(exists){
console.log('exists: ', exists);
// => true
});
path.exists('/does_not_exist', function(exists){
console.log('exists: ', exists);
// => false
});
// In Node v0.8, path.exists wall replaced by fs.exists
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment