Skip to content

Instantly share code, notes, and snippets.

@leommoore
Last active August 19, 2024 13:02
Show Gist options
  • Save leommoore/4483842 to your computer and use it in GitHub Desktop.
Save leommoore/4483842 to your computer and use it in GitHub Desktop.
Node - File Paths

#Node - File Paths

##File Paths Node has a path module which can be used to manipulate paths.

###Normalizing Paths Paths can be stored in different ways and it is neccessary to ensure that the path is standardized.

var path = require('path');
path.normalize('/foo/bar//baz/asdf/quux/..');
// = '/foo/bar/baz/asdf'

###Joining Paths Use path.join() to join two or more paths. It also will normalize the path.

var path = require('path');
path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// = '/foo/bar/baz/asdf'

###Finding the Relative Path Between Two Absolute Paths By using the path.relative(), you can get the relative path from one absolute path to another.

var path = require('path');
path.relative('/data/maps/us/alaska', 'data/maps/europe/albania');
// = ../../europe/albania

###Extracting Path Information

####Directory

var path = require('path');
path.dirname('/data/maps/us/alaska/map.dat');
// = /data/maps/us/alaska

####Filename

var path = require('path');
path.basename('/data/maps/us/alaska/map.dat');
// = map.dat

####Filename without extension

var path = require('path');
path.basename('/data/maps/us/alaska/map.dat','.dat');
// = map

####File Extension

var path = require('path');
path.extname('/data/maps/us/alaska/map.dat');
// = '.dat'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment