From understanding what Node.js and the current script are, to knowing how to get a path to the current script with Node.js, this article will help you.
Also Read: Asynchronous Programming in Node.js
Overview of Node.js
Read More: What is Node.js?
What is Current Script?
Scripts on a computer are like sets of instructions. They serve as a structured series of commands or actions that dictate how a particular task should be carried out. Scripting, in essence, is the process of creating these sets of instructions to automate various processes and achieve specific goals. Scripts can range from simple, one-time-use commands to complex, reusable programs that facilitate tasks and workflows.
With this small introduction, let’s see the process of getting its path in Node.js.
Getting the Path to the Current Script in Node.js
There are two ways to get the path to the current script in Node.js. The first one is using __dirname while the other is using process.cwd(). We have discussed both of these methods below.
Using the above code, we can find out the absolute path of the current script’s directory.
Get the path with the file name:
The path.dirname() method, when used in conjunction with the __filename module, can give you an outcome with the filename as well along with the name of the directory.
Additionally, we can provide a path to the path.dirname() function to obtain the directory where the path is located. The __filename module supplies the complete path to the current file.
process.cwd() is a Node.js method for obtaining the Node.js process’s current working directory (CWD). It returns the directory where the Node.js process was started. It can change if the Node.js process is launched from a different directory rather __dirname, which always points to the script’s directory.
It reflects the directory in which the Node.js process is running, which may or may not be the same as the directory in which the script is located. It is primarily used to determine the Node.js process’s current working directory, which is useful when accessing files or resources relative to the process’s current directory.
Using the above code, we get a similar outcome as the one with the above method i.e. using __dirname.
Scripts are tools used by developers to streamline the processes and workflows. Thus, getting the path to the current script is an essential step in the development process. In order to get the path to the current script we can use two methods that are either using __dirname or process.cwd(). Both of these methods provide the path to the directory where the current script is located. We can use path.dirname() in conjunction with the __filename module to get the complete path along with the path to the file containing the current script.