Skip to content

File and process functions#

These functions read and write files and run programs on the machine that runs the script. You can use them in 9Login scripts and when you test in Studio. In 9Hits campaign macros, every function on this page is blocked and returns {error: "Blocked"}.

Warning

These functions act for real on your machine and cannot be undone. Always use absolute paths, and double-check any script that contains DelFileOrDir or LaunchProcess before you run it.

The functions on this page finish right away, so they do not need await. Most of them return an object: the result is in result and the error is in error.

ReadFileAsString #

Reads an entire text file (UTF-8) into a string. For binary files such as images, use ReadFileAsBytes, because reading them with this function corrupts the data.

Syntax
ReadFileAsString(path);
Parameters
Name Description
path Absolute path to the file, for example "C:/data/list.txt". If it is empty or not a string, the function returns {error}.
Returns

{result: string} with the file content when the read succeeds; {error} on failure, with the reason in error.

Example
1
2
3
4
5
6
7
8
// read a list, one item per line
const r = ReadFileAsString("C:/data/list.txt");
if (r.error) Log("File read error:", r.error);
else {
    const lines = r.result.split(/\r?\n/);
    Log("Line count:", lines.length);
}
// r = {result: "line 1\nline 2"}

ReadFileAsBytes #

Reads an entire file as binary data, for images and other non-text files. The whole file is loaded into memory at once, so avoid using it on very large files.

Syntax
ReadFileAsBytes(path);
Parameters
Name Description
path Absolute path to the file, for example "C:/data/image.png". If it is empty or not a string, the function returns {error}.
Returns

{result: ArrayBuffer} when the read succeeds; {error} on failure. result is not a string: to print it or send it somewhere as a string, convert it with Base64Encode.

Example
1
2
3
4
5
6
7
// read an image, then convert it to base64 to send it
const r = ReadFileAsBytes("C:/data/image.png");
if (r.error) Log("File read error:", r.error);
else {
    const b64 = Base64Encode(r.result);
    Log("Base64 length:", b64.length);
}

WriteFile #

Writes data to a file: creates the file if it does not exist, and overwrites it completely if it does. Missing parent folders are created too. The function has no append mode; to add to the end of a file, read the old content, append to it and write it back (see the example).

Syntax
WriteFile(path, data);
Parameters
Name Description
path Absolute path of the file to write. If it is empty or not a string, the function returns {error}.
data Content to write: a string, or an ArrayBuffer for binary data. Numbers and objects are not converted automatically; they are rejected with {error}. Convert them to a string first, for example with JSON.stringify.
Returns

{error} on failure; no error means the write is done.

Example
1
2
3
4
5
6
7
// write an object to a JSON file
const r = WriteFile("C:/data/result.json", JSON.stringify({ok: true}));
if (r.error) Log("File write error:", r.error);

// add a line to the end of a log file
const old = ReadFileAsString("C:/data/log.txt");
WriteFile("C:/data/log.txt", (old.result || "") + "Done at " + new Date().toISOString() + "\n");

TouchFile #

Sets the modification time and access time of a file to the current time without changing its content. The file must already exist: the function does not create a new file, it returns {error}.

Syntax
TouchFile(path);
Parameters
Name Description
path Absolute path to an existing file.
Returns

{error} on failure, including when the file does not exist; no error means the times were updated.

Example
1
2
3
// mark the last run with the file's modification time
const r = TouchFile("C:/data/marker.txt");
if (r.error) WriteFile("C:/data/marker.txt", ""); // create an empty file if it does not exist yet

ReadDir #

Lists the files and subfolders directly inside a folder. Each item is a full path, not just a name. The function does not tell you which items are folders; to find out, call GetFileInfo on each item.

Syntax
ReadDir(path);
Parameters
Name Description
path Absolute path of the folder to list.
Returns

{result: string[]}, an array of full paths, when the read succeeds; {error} on failure.

Example
1
2
3
4
5
6
7
// print the names of the .txt files in a folder
const r = ReadDir("C:/data");
for (const p of (r.result || [])) {
    const name = p.split(/[\\/]/).pop(); // get the name from the full path
    if (name.endsWith(".txt")) Log(name);
}
// r = {result: ["C:/data/list.txt", "C:/data/exports"]}

MkDir #

Creates a folder, including any missing parent folders. A folder that already exists does not count as an error.

Syntax
MkDir(path);
Parameters
Name Description
path Absolute path of the folder to create.
Returns

{error} on failure; no error means the folder exists (just created or already there).

Example
1
2
3
4
// create a folder per date to store results
const dir = "C:/data/exports/" + new Date().toISOString().slice(0, 10);
const r = MkDir(dir);
if (r.error) Log("Could not create the folder:", r.error);

DelFileOrDir #

Deletes a file, or a folder and everything inside it. The function deletes right away, without asking and without undo, so double-check the path before you call it.

Syntax
DelFileOrDir(path);
Parameters
Name Description
path Absolute path of the file or folder to delete.
Returns

{error} on failure; no error means it was deleted.

Example
1
2
3
4
5
6
// delete a file
DelFileOrDir("C:/data/exports/old.txt");

// delete a temp folder and everything inside it
const r = DelFileOrDir("C:/data/tmp");
if (r.error) Log("Could not delete:", r.error);

CopyFileOrDir #

Copies a file, or a whole folder and everything inside it, from src to dst.

Syntax
CopyFileOrDir(src, dst);
Parameters
Name Description
src Absolute path of the source file or folder.
dst Absolute path of the copy. If it is the same as src, the function returns {error}.
Returns

{error} on failure; no error means the copy is done.

Example
1
2
3
4
5
6
// back up the config file before editing it
const r = CopyFileOrDir("C:/data/config.json", "C:/data/config.bak.json");
if (r.error) Log("Could not back up:", r.error);

// copy a whole folder
CopyFileOrDir("C:/data/template", "C:/data/job-01");

MoveFileOrDir #

Moves a file or folder from src to dst. This is also how you rename: move it to a new name in the same folder.

Syntax
MoveFileOrDir(src, dst);
Parameters
Name Description
src Absolute path of the file or folder to move.
dst New absolute path. If it is the same as src, the function returns {error}.
Returns

{error} on failure; no error means the move is done.

Example
1
2
3
4
5
6
// rename a file once it has been processed
MoveFileOrDir("C:/data/tmp.txt", "C:/data/done.txt");

// move a file to another folder
const r = MoveFileOrDir("C:/data/report.csv", "C:/archive/report.csv");
if (r.error) Log("Could not move:", r.error);

PathExists #

Checks whether a file or folder exists. The function does not tell files from folders; to find out, use GetFileInfo.

Syntax
PathExists(path);
Parameters
Name Description
path Absolute path to check.
Returns

true or false. The exception: when the path is empty or not a string, the function returns an {error} object, not false. An object always counts as true in an if, so compare with === true.

Example
1
2
3
4
// create a default config file if there is none yet
if (PathExists("C:/data/config.json") !== true) {
    WriteFile("C:/data/config.json", "{}");
}

GetFileInfo #

Reads information about a file or folder: size, type and timestamps. If the path does not exist, the function returns {error}, so you can use it both to check that a path exists and to tell whether it is a file or a folder.

Syntax
GetFileInfo(path);
Parameters
Name Description
path Absolute path of the file or folder.
Returns

{result: {size, isDirectory, isSymbolicLink, creationTime, lastModified, lastAccessed}} when the read succeeds; {error} on failure or when the path does not exist.

  • size: size in bytes.
  • isDirectory, isSymbolicLink: true or false.
  • creationTime, lastModified, lastAccessed: time in seconds since 1970.
Example
1
2
3
4
5
6
7
const r = GetFileInfo("C:/data/config.json");
if (r.error) Log("Could not read:", r.error);
else {
    Log("Size:", r.result.size, "bytes");
    Log("Created at:", new Date(r.result.creationTime * 1000).toLocaleString());
}
// r = {result: {size: 2048, isDirectory: false, isSymbolicLink: false, creationTime: 1760000000, ...}}

GetCurrentDir #

Returns the working directory of the session that runs the script.

Syntax
GetCurrentDir();
Returns

A path string, not wrapped in an object like the other functions on this page.

Example
const dir = GetCurrentDir();
Log("Working directory:", dir);

GetHomeDir #

Returns the user's home directory on the machine, for example C:\Users\<name> on Windows.

Syntax
GetHomeDir();
Returns

A path string, not wrapped in an object.

Example
1
2
3
// save the result to the user's Documents folder
const home = GetHomeDir();
WriteFile(home + "/Documents/9hits-result.txt", "ok");

GetDownloadDir #

Returns the folder where the session saves downloaded files.

Syntax
GetDownloadDir();
Returns

A path string, not wrapped in an object; null when the session has no download folder of its own.

Example
1
2
3
4
5
6
// list the downloaded files
const dl = GetDownloadDir();
if (dl) {
    const r = ReadDir(dl);
    for (const p of (r.result || [])) Log(p);
}

LaunchProcess #

Runs a program on the machine, for example a command-line tool or an application. You can start it and move on right away, or wait for the program to finish and get what it printed. While it waits, the script stops at that line until the program exits, so do not wait for a program that does not exit on its own (such as Notepad).

Syntax
LaunchProcess(cmd, args, wait=false);
Parameters
Name Description
cmd Program to run: a path to an executable, or a program name such as "notepad.exe".
args Array of command-line arguments, one argument per item, for example ["/c", "dir"]. With no arguments, pass []. If it is not an array, the function returns {error}.
wait true to wait for the program to finish before moving on; false to start it and move on right away. Default false.
Returns

{result} or {error}. When wait is true, result is what the program printed.

Example
1
2
3
4
5
6
7
// open Notepad and move on right away
LaunchProcess("notepad.exe", []);

// run a command, wait for it to finish, then get what it printed
const r = LaunchProcess("cmd.exe", ["/c", "dir C:\\data"], true);
if (r.error) Log("Error:", r.error);
else Log(r.result);