Working with File Paths in Node.js
This article discusses handling file paths from the file system, which is important for loading and parsing file names in your application.
The file system is a big part of any application that has to handle files paths for loading, manipulating, or serving data. Node provides some helper methods for working with file paths, which are discussed in the sections that follow.
Most of the time, your application has to know where certain files and/or directories are and executes them within the file system based on certain contexts. Most other languages also have these convenience methods, but Node may have a few you might not have seen with any other language.
Find Paths
Node can tell you where in the file system it is working by using the _filename and _dirname variables. The _filename variable provides the absolute path to the file that is currently executing; _dirname provides the absolute path to the working directory where the file being executed is located. Neither variable has to be imported from any modules because each is provided standard.
A simple example using both variables appears below:
console.log("This file is " + __filename); console.log("It's located in " + __dirname);
The output from this code from my machine is this:
This file is C:\Users\Jesse Smith\workspacex\IntroToNode\file1.js It is located in C:\Users\Jesse Smith\workspacex\IntroToNode
You can use the process object’s cwd() method to get the current working directory of the application:
console.log("The current working directory is " + process.cwd());
Many applications might have to switch the current working directory to another directory to fetch or serve different files. The process object provides the chdir() method to accomplish this. The name of the directory to switch to is passed in as an argument to this method:
process.chdir("../"); console.log("The new working directory is " + process.cwd());
The code changes to the directory above the current working directory. If the directory name change fails, the current working directory remains the working directory. You can trap for this error using a try..catch clause.
You might you need the path to the Node executable file. The process object provides the execPath() method to achieve this:
console.log(process.execPath);
The output from the code above is the path C:\Program Files (x86)\nodejs\node.exe.