Skip to content

Core\Path::thisFile

Core\Path::thisFile(): string

Returns the full path of the source file that contains the call.

The compiler writes the path in place of the call, so the call does no work when the program runs. The path is the same from every folder you start the program in. A call in a file that you load with require returns the path of that file, not the path of the first file. Use Core\Path::thisDirectory for the folder of the file.

Good to know: the full path is different on every computer. Print Core\Path::fileName of it when you only need the file name.

The examples below print the name of the file, compare its folder with Core\Path::thisDirectory, and put the name of a tool into its usage message.

Return value

Returns string. The full path of the file, written with Core\Path::SEPARATOR. In a bundled program, the folder is the one beside the executable.

Errors

  • RuntimeErrorThe source was given to the compiler as text, so there is no file to name.

Examples

The name of this file

<?nvs
// Shows how a program gets the full path of its own source file.
string $file = Core\Path::thisFile();
// The path starts at a root, so this prints `true`.
echo Core\Path::isAbsolute($file) ? 'true' : 'false', "\n";
// `fileName` gives the last part of the path.
// This prints `01-the-name-of-this-file.nvs`.
echo Core\Path::fileName($file), "\n";
Output
true
01-the-name-of-this-file.nvs

The folder of this file

<?nvs
// Shows that the folder of `thisFile` is the folder that `thisDirectory` returns.
string $folder = Core\Path::parent(Core\Path::thisFile());
// The file is in a folder named `thisFile`, so this prints `thisFile`.
echo Core\Path::fileName($folder), "\n";
// `normalize` writes both paths the same way before they are compared.
// This prints `same folder`.
echo Core\Path::normalize($folder) == Core\Path::normalize(Core\Path::thisDirectory())
? 'same folder'
: 'different folder', "\n";
Output
thisFile
same folder

A usage message with the file name

<?nvs
// Shows how a command-line tool puts its own file name into its usage message.
array<tainted string> $words = Core\Cli::arguments();
// The tool needs one file name. When it gets none, it prints how to start it.
// This prints `Usage: nvs run 03-a-usage-message-with-the-file-name.nvs <file>`.
if (Core\Arr::count($words) == 0) {
string $name = Core\Path::fileName(Core\Path::thisFile());
echo 'Usage: nvs run ', $name, " <file>\n";
}
Output
Usage: nvs run 03-a-usage-message-with-the-file-name.nvs <file>