Readonly argsArguments passed into the script.
RAM cost: 0 GB
Arguments passed into a script can be accessed as a normal array by using the [] operator
(args[0], args[1], etc...).
Arguments can be string, number, or boolean.
Use args.length to get the number of arguments that were passed into a script.
run example.js 7 text true
// example.js
export async function main(ns) {
ns.tprint(ns.args.length) // 3
ns.tprint(ns.args[0]); // 7 (number)
ns.tprint(ns.args[1]); // "text" (string)
ns.tprint(ns.args[2]); // true (boolean)
ns.tprint(ns.args[3]); // undefined, because only 3 arguments were provided
}
Readonly bladeburnerNamespace for bladeburner functions. Contains spoilers.
RAM cost: 0 GB
Readonly codingcontractNamespace for codingcontract functions.
RAM cost: 0 GB
Readonly corporationNamespace for corporation functions. Contains spoilers.
RAM cost: 0 GB
Readonly formulasNamespace for formulas functions.
RAM cost: 0 GB
Readonly gangNamespace for gang functions. Contains spoilers.
RAM cost: 0 GB
Readonly goNamespace for Go functions.
RAM cost: 0 GB
Readonly graftingNamespace for grafting functions. Contains spoilers.
RAM cost: 0 GB
Readonly hacknetNamespace for hacknet functions. Some of this API contains spoilers.
RAM cost: 4 GB.
Readonly heartReadonly infiltrationNamespace for infiltration functions.
RAM cost: 0 GB
Readonly pidThe current script's PID
Readonly singularityNamespace for singularity functions. Contains spoilers.
RAM cost: 0 GB
Readonly sleeveNamespace for sleeve functions. Contains spoilers.
RAM cost: 0 GB
Readonly stanekNamespace for stanek functions. Contains spoilers.
RAM cost: 0 GB
Readonly stockNamespace for stock functions.
RAM cost: 0 GB
Readonly uiNamespace for user interface functions.
RAM cost: 0 GB
Close the tail window of a script.
Optional pid: numberOptional. PID of the script having its tail closed. If omitted, the current script is used.
RAM cost: 0 GB
Closes a script’s logs. This is functionally the same as pressing the "Close" button on the tail window.
If the function is called with no arguments, it will close the current script’s logs.
Otherwise, the pid argument can be used to close the logs from another script.
Delete a purchased server.
Hostname of the server to delete.
True if successful, and false otherwise.
2.25 GB
Deletes one of your purchased servers, which is specified by its hostname.
The hostname argument can be any data type, but it will be converted to a string. Whitespace is automatically removed from the string. This function will not delete a server that still has scripts running on it.
Disables logging for the given function.
Name of function for which to disable logging.
RAM cost: 0 GB
Logging can be disabled for all functions by passing ALL as the argument.
For specific interfaces, use the form "namespace.functionName". (e.g. "ui.setTheme")
Enable logging for a certain function.
Name of function for which to enable logging.
RAM cost: 0 GB
Re-enables logging for the given function. If ALL is passed into this
function as an argument, then it will revert the effects of disableLog(ALL).
Start another script on any server.
Filename of script to execute. This file must already exist on the target server.
Hostname of the target server on which to execute the script.
Optional threadOrOptions: number | RunOptionsEither an integer number of threads for new script, or a RunOptions object. Threads defaults to 1.
Rest ...args: ScriptArg[]Additional arguments to pass into the new script that is being run. Note that if any arguments are being passed into the new script, then the third argument threadOrOptions must be filled in with a value.
Returns the PID of a successfully started script, and 0 otherwise.
RAM cost: 1.3 GB
Run a script as a separate process on a specified server. This is similar to the function run except that it can be used to run a script that already exists on any server, instead of just the current server.
If the script was successfully started, then this function returns the PID of that script. Otherwise, it returns 0.
PID stands for Process ID. The PID is a unique identifier for each script. The PID will always be a positive integer.
Running this function with 0 or fewer threads will cause a runtime error.
// The simplest way to use the exec command is to call it with just the script name
// and the target server. The following example will try to run generic-hack.js
// on the foodnstuff server.
ns.exec("generic-hack.js", "foodnstuff");
// The following example will try to run the script generic-hack.js on the
// joesguns server with 10 threads.
ns.exec("generic-hack.js", "joesguns", {threads: 10});
// This last example will try to run the script foo.js on the foodnstuff server
// with 5 threads. It will also pass the number 1 and the string “test” in as
// arguments to the script.
ns.exec("foo.js", "foodnstuff", 5, 1, "test");
Check if a file exists.
Filename of file to check.
Optional host: stringHost of target server. Optional, defaults to the server the script is running on.
True if specified file exists, and false otherwise.
RAM cost: 0.1 GB
Returns a boolean indicating whether the specified file exists on the target server. The filename for programs is case-insensitive, other file types are case-sensitive. For example, fileExists(“brutessh.exe”) will work fine, even though the actual program is named 'BruteSSH.exe'.
// The function call will return true if the script named foo.js exists on the foodnstuff server, and false otherwise.
ns.fileExists("foo.js", "foodnstuff");
// The function call will return true if the current server contains the FTPCrack.exe program, and false otherwise.
ns.fileExists("ftpcrack.exe");
Parse command line flags.
RAM cost: 0 GB
Allows Unix-like flag parsing.
export async function main(ns) {
const data = ns.flags([
['delay', 0], // a default number means this flag is a number
['server', 'foodnstuff'], // a default string means this flag is a string
['exclude', []], // a default array means this flag is a default array of string
['help', false], // a default boolean means this flag is a boolean
]);
ns.tprint(data);
}
// [home ~/]> run example.js
// {"_":[],"delay":0,"server":"foodnstuff","exclude":[],"help":false}
// [home ~/]> run example.js --delay 3000
// {"_":[],"server":"foodnstuff","exclude":[],"help":false,"delay":3000}
// [home ~/]> run example.js --delay 3000 --server harakiri-sushi
// {"_":[],"exclude":[],"help":false,"delay":3000,"server":"harakiri-sushi"}
// [home ~/]> run example.js --delay 3000 --server harakiri-sushi hello world
// {"_":["hello","world"],"exclude":[],"help":false,"delay":3000,"server":"harakiri-sushi"}
// [home ~/]> run example.js --delay 3000 --server harakiri-sushi hello world --exclude a --exclude b
// {"_":["hello","world"],"help":false,"delay":3000,"server":"harakiri-sushi","exclude":["a","b"]}
// [home ~/]> run example.script --help
// {"_":[],"delay":0,"server":"foodnstuff","exclude":[],"help":true}
Format a number.
Number to format.
Optional fractionalDigits: numberNumber of digits to show in the fractional part of the decimal number. Optional, defaults to 3.
Optional suffixStart: numberHow high a number must be before a suffix will be added. Optional, defaults to 1000.
Optional isInteger: booleanWhether the number represents an integer. Integers do not display fractional digits until a suffix is present. Optional, defaults to false.
Formatted number.
RAM cost: 0 GB
Converts a number into a numeric string with the specified format options. This is the same function that the game itself uses to display numbers. The format also depends on the Numeric Display settings (all options on the "Numeric Display" options page) To format ram or percentages, see formatRam and formatPercent
Format a number as a percentage.
Number to format as a percentage.
Optional fractionalDigits: numberNumber of digits to show in the fractional part of the decimal number. Optional, defaults to 2.
Optional suffixStart: numberWhen to switch the percentage to a multiplier. Default is 1e6 or x1.00m.
Formatted percentage.
RAM cost: 0 GB
Converts a number into a percentage string with the specified number of fractional digits. This is the same function that the game itself uses to display percentages. The format also depends on the Numeric Display settings (all options on the "Numeric Display" options page) To format plain numbers or ram, see formatNumber and formatRam
Format a number as an amount of ram.
Number to format as an amount of ram, in base units of GB (or GiB if that Numeric Display option is set).
Optional fractionalDigits: numberNumber of digits to show in the fractional part of the decimal number. Optional, defaults to 2.
Formatted ram amount.
RAM cost: 0 GB
Converts a number into a ram string with the specified number of fractional digits. This is the same function that the game itself uses to display ram. The format also depends on the Numeric Display settings (all options on the "Numeric Display" options page) To format plain numbers or percentages, see formatNumber and formatPercent
Get the current Bitnode multipliers.
Optional n: numberOptional lvl: numberObject containing the current BitNode multipliers.
RAM cost: 4 GB
Returns an object containing the current (or supplied) BitNode multipliers. This function requires you to be in Bitnode 5 or have Source-File 5 in order to run. The multipliers are returned in decimal forms (e.g. 1.5 instead of 150%). The multipliers represent the difference between the current BitNode and the original BitNode (BitNode-1).
For example, if the CrimeMoney multiplier has a value of 0.1, then that means that committing crimes in the current BitNode will only give 10% of the money you would have received in BitNode-1.
const mults = ns.getBitNodeMultipliers();
ns.tprint(`ServerMaxMoney: ${mults.ServerMaxMoney}`);
ns.tprint(`HackExpGain: ${mults.HackExpGain}`);
Get the execution time of a grow() call.
Hostname of target server.
Returns the amount of time in milliseconds it takes to execute the grow Netscript function.
RAM cost: 0.05 GB
Returns the amount of time in milliseconds it takes to execute the grow Netscript function on the target server. The required time is increased by the security level of the target server and decreased by the player's hacking level.
Get the execution time of a hack() call.
Hostname of target server.
Returns the amount of time in milliseconds it takes to execute the hack Netscript function.
RAM cost: 0.05 GB
When hack completes an amount of money is stolen depending on the player's skills.
Returns the amount of time in milliseconds it takes to execute the hack Netscript function on the target server.
The required time is increased by the security level of the target server and decreased by the player's hacking level.
Get hacking related multipliers.
Object containing the Player’s hacking related multipliers.
RAM cost: 0.25 GB
Returns an object containing the Player’s hacking related multipliers. These multipliers are returned in fractional forms, not percentages (e.g. 1.5 instead of 150%).
const mults = ns.getHackingMultipliers();
print(`chance: ${mults.chance}`);
print(`growth: ${mults.growth}`);
Get hacknet related multipliers.
Object containing the Player’s hacknet related multipliers.
RAM cost: 0.25 GB
Returns an object containing the Player’s hacknet related multipliers. These multipliers are returned in fractional forms, not percentages (e.g. 1.5 instead of 150%).
const mults = ns.getHacknetMultipliers();
ns.tprint(`production: ${mults.production}`);
ns.tprint(`purchaseCost: ${mults.purchaseCost}`);
Get information about the sources of income for this run.
Money sources
RAM cost: 1.0 GB
Returns an object with information on the income sources for this run
Get all data on a port.
Port number. Must be a positive integer.
RAM cost: 0 GB
Get a handle to a Netscript Port.
WARNING: Port Handles only work in NetscriptJS (Netscript 2.0). They will not work in Netscript 1.0.
Get cost of purchasing a server.
Amount of RAM of a potential purchased server, in GB. Must be a power of 2 (2, 4, 8, 16, etc.). Maximum value of 1048576 (2^20).
The cost to purchase a server with the specified amount of ram.
RAM cost: 0.25 GB
Returns the cost to purchase a server with the specified amount of ram.
const ram = 2 ** 20;
const cost = ns.getPurchasedServerCost(ram);
ns.tprint(`A purchased server with ${ns.formatRam(ram)} costs ${ns.formatMoney(cost)}`);
Get cost of upgrading a purchased server to the given ram.
Hostname of the server to upgrade.
Amount of RAM of the purchased server, in GB. Must be a power of 2 (2, 4, 8, 16, etc.). Maximum value of 1048576 (2^20).
The price to upgrade.
RAM cost: 0.1 GB
Get an array of recently killed scripts across all servers.
Array with information about previously killed scripts.
RAM cost: 0.2 GB
The most recently killed script is the first element in the array.
Note that there is a maximum number of recently killed scripts which are tracked.
This is configurable in the game's options as Recently killed scripts size.
let recentScripts = ns.getRecentScripts();
let mostRecent = recentScripts.shift()
if (mostRecent)
ns.tprint(mostRecent.logs.join('\n'))
Get information about resets.
RAM cost: 1 GB
const resetInfo = ns.getResetInfo();
const lastAugReset = resetInfo.lastAugReset;
ns.tprint(`The last augmentation reset was: ${new Date(lastAugReset)}`);
ns.tprint(`It has been ${Date.now() - lastAugReset}ms since the last augmentation reset.`);
Get general info about a running script.
Optional filename: FilenameOrPIDOptional. Filename or PID of the script.
Optional hostname: stringHostname of target server. Optional, defaults to the server the calling script is running on.
Rest ...args: ScriptArg[]Arguments to specify/identify the script. Optional, when looking for scripts run without arguments.
The info about the running script if found, and null otherwise.
RAM cost: 0.3 GB
Running with no args returns current script. If you use a PID as the first parameter, the hostname and args parameters are unnecessary. If hostname is omitted while filename is used as the first parameter, hostname defaults to the server the calling script is running on. Remember that a script is semi-uniquely identified by both its name and its arguments. (You can run multiple copies of scripts with the same arguments, but for the purposes of functions like this that check based on filename, the filename plus arguments forms the key.)
Get the exp gain of a script.
Filename of script.
Server on which script is running.
Rest ...args: ScriptArg[]Arguments that the script is running with.
Amount of hacking experience the specified script generates while online.
RAM cost: 0.1 GB
Returns the amount of hacking experience the specified script generates while online (when the game is open, does not apply for offline experience gains). Remember that a script is uniquely identified by both its name and its arguments.
This function can also return the total experience gain rate of all of your active scripts by running the function with no arguments.
Get the income of a script.
Filename of script.
Server on which script is running.
Rest ...args: ScriptArg[]Arguments that the script is running with.
Amount of income the specified script generates while online.
RAM cost: 0.1 GB
Returns the amount of income the specified script generates while online (when the game is open, does not apply for offline income). Remember that a script is uniquely identified by both its name and its arguments. So for example if you ran a script with the arguments “foodnstuff” and “5” then in order to use this function to get that script’s income you must specify those same arguments in the same order in this function call.
Get all the logs of a script.
Optional fn: FilenameOrPIDOptional. Filename or PID of script to get logs from.
Optional host: stringOptional. Hostname of the server that the script is on.
Rest ...args: ScriptArg[]Arguments to identify which scripts to get logs for.
Returns a string array, where each line is an element in the array. The most recently logged line is at the end of the array.
RAM cost: 0 GB
Returns a script’s logs. The logs are returned as an array, where each line is an element in the array. The most recently logged line is at the end of the array. Note that there is a maximum number of lines that a script stores in its logs. This is configurable in the game’s options. If the function is called with no arguments, it will return the current script’s logs.
Otherwise, the PID or filename, hostname/ip, and args… arguments can be used to get logs from another script. Remember that scripts are uniquely identified by both their names and arguments.
//Get logs from foo.js on the current server that was run with no args
ns.getScriptLogs("foo.js");
//Open logs from foo.js on the foodnstuff server that was run with no args
ns.getScriptLogs("foo.js", "foodnstuff");
//Open logs from foo.js on the foodnstuff server that was run with the arguments [1, "test"]
ns.getScriptLogs("foo.js", "foodnstuff", 1, "test");
Get the ram cost of a script.
Filename of script. This is case-sensitive.
Optional host: stringHostname of target server the script is located on. This is optional. If it is not specified then the function will use the current server as the target server.
Amount of RAM (in GB) required to run the specified script on the target server, and 0 if the script does not exist.
RAM cost: 0.1 GB
Returns the amount of RAM required to run the specified script on the target server. Returns 0 if the script does not exist.
Get the base security level of a server.
Host of target server.
Base security level of the target server.
RAM cost: 0.1 GB Returns the base security level of the target server. For the server's actual security level, use ns.getServerSecurityLevel.
Get a server growth parameter.
Hostname of target server.
Parameter that affects the percentage by which the server’s money is increased when using the grow function.
RAM cost: 0.1 GB
Returns the server’s intrinsic “growth parameter”. This growth parameter is a number typically between 0 and 100 that represents how quickly the server’s money grows. This parameter affects the percentage by which the server’s money is increased when using the grow function. A higher growth parameter will result in a higher percentage increase from grow.
Get money available on a server.
Hostname of target server.
Amount of money available on the server.
RAM cost: 0.1 GB
Returns the amount of money available on a server. Running this function on the home computer will return the player’s money.
ns.getServerMoneyAvailable("foodnstuff");
ns.getServerMoneyAvailable("home"); // Returns player's money
Returns the number of open ports required to successfully run NUKE.exe on the specified server.
Hostname of target server.
The number of open ports required to successfully run NUKE.exe on the specified server.
RAM cost: 0.1 GB
Get server security level.
Hostname of target server.
Security level of the target server.
RAM cost: 0.1 GB
Returns the security level of the target server. A server’s security level is denoted by a number, typically between 1 and 100 (but it can go above 100).
Get the income of all scripts.
An array of two values. The first value is the total income (dollar / second) of all of your active scripts (scripts that are currently running on any server). The second value is the total income (dollar / second) that you’ve earned from scripts since you last installed Augmentations.
RAM cost: 0.1 GB
Get the execution time of a weaken() call.
Hostname of target server.
Returns the amount of time in milliseconds it takes to execute the weaken Netscript function.
RAM cost: 0.05 GB
Returns the amount of time in milliseconds it takes to execute the weaken Netscript function on the target server. The required time is increased by the security level of the target server and decreased by the player's hacking level.
Spoof money in a server's bank account, increasing the amount available.
Hostname of the target server to grow.
Optional opts: BasicHGWOptionsOptional parameters for configuring function behavior.
The total effective multiplier that was applied to the server's money (after both additive and multiplicative growth).
RAM cost: 0.15 GB
Use your hacking skills to increase the amount of money available on a server.
Once the grow is complete, $1 is added to the server's available money for every script thread. This additive growth allows for rescuing a server even after it is emptied.
After this addition, the thread count is also used to determine a multiplier, which the server's money is then multiplied by.
The multiplier scales exponentially with thread count, and its base depends on the server's security level and in inherent "growth" statistic that varies between different servers.
getServerGrowth can be used to check the inherent growth statistic of a server.
growthAnalyze can be used to determine the number of threads needed for a specified multiplicative portion of server growth.
To determine the effect of a single grow, obtain access to the Formulas API and use formulas.hacking.growPercent, or invert growthAnalyze.
To determine how many threads are needed to return a server to max money, obtain access to the Formulas API and use formulas.hacking.growThreads, or NS.growthAnalyze if the server will be at the same security in the future.
Like hack, grow can be called on any hackable server, regardless of where the script is
running. Hackable servers are any servers not owned by the player.
The grow() command requires root access to the target server, but there is no required hacking level to run the command. It also raises the security level of the target server based on the number of threads. The security increase can be determined using growthAnalyzeSecurity.
let currentMoney = ns.getServerMoneyAvailable("n00dles");
currentMoney *= await ns.grow("foodnstuff");
Calculate the number of grow threads needed for a given multiplicative growth factor.
Hostname of the target server.
Multiplier that will be applied to a server's money after applying additive growth. Decimal form.
Optional cores: numberNumber of cores on the host running the grow function. Optional, defaults to 1.
Decimal number of grow threads needed for the specified multiplicative growth factor (does not include additive growth).
RAM cost: 1 GB
This function returns the total decimal number of grow threads needed in order to multiply the money available on the specified server by a given multiplier, if all threads are executed at the server's current security level, regardless of how many threads are assigned to each call.
Note that there is also an additive factor that is applied before the multiplier. Each grow call will add $1 to the host's money for each thread before applying the multiplier for its thread count. This means that at extremely low starting money, fewer threads would be needed to apply the same effective multiplier than what is calculated by growthAnalyze.
Like other basic hacking analysis functions, this calculation uses the current status of the player and server. To calculate using hypothetical server or player status, obtain access to the Formulas API and use formulas.hacking.growThreads.
// calculate number of grow threads to apply 2x growth multiplier on n00dles (does not include the additive growth).
const growThreads = ns.growthAnalyze("n00dles", 2);
// When using the thread count to launch a script, it needs to be converted to an integer.
ns.run("noodleGrow.js", Math.ceil(growThreads));
Calculate the security increase for a number of grow threads.
Amount of threads that will be used.
Optional hostname: stringOptional. Hostname of the target server. If provided, security increase is limited by the number of threads needed to reach maximum money.
Optional cores: numberOptional. The number of cores of the server that would run grow.
The security increase.
RAM cost: 1 GB
Returns the security increase that would occur if a grow with this many threads happened.
Steal a server's money.
Hostname of the target server to hack.
Optional opts: BasicHGWOptionsOptional parameters for configuring function behavior.
A promise that resolves to the amount of money stolen (which is zero if the hack is unsuccessful).
RAM cost: 0.1 GB
Function that is used to try and hack servers to steal money and gain hacking experience. The runtime for this command depends on your hacking level and the target server’s security level when this function is called. In order to hack a server you must first gain root access to that server and also have the required hacking level.
A script can hack a server from anywhere. It does not need to be running on the same
server to hack that server. For example, you can create a script that hacks the foodnstuff
server and run that script on any server in the game.
A successful hack() on a server will raise that server’s security level by 0.002.
let earnedMoney = await ns.hack("foodnstuff");
Get the part of money stolen with a single thread.
Hostname of the target server.
The part of money you will steal from the target server with a single thread hack.
RAM cost: 1 GB
Returns the part of the specified server’s money you will steal with a single thread hack.
Like other basic hacking analysis functions, this calculation uses the current status of the player and server. To calculate using hypothetical server or player status, obtain access to the Formulas API and use formulas.hacking.hackPercent.
//For example, assume the following returns 0.01:
const hackAmount = ns.hackAnalyze("foodnstuff");
//This means that if hack the foodnstuff server using a single thread, then you will steal 1%, or 0.01 of its total money. If you hack using N threads, then you will steal N*0.01 times its total money.
Get the chance of successfully hacking a server.
Hostname of the target server.
The chance you have of successfully hacking the target server.
RAM cost: 1 GB
Returns the chance you have of successfully hacking the specified server.
This returned value is in decimal form, not percentage.
Like other basic hacking analysis functions, this calculation uses the current status of the player and server. To calculate using hypothetical server or player status, obtain access to the Formulas API and use formulas.hacking.hackChance.
Get the security increase for a number of threads.
Amount of threads that will be used.
Optional hostname: stringHostname of the target server. The number of threads is limited to the number needed to hack the server's maximum amount of money.
The security increase.
RAM cost: 1 GB
Returns the security increase that would occur if a hack with this many threads happened.
Calculate the decimal number of threads needed to hack a specified amount of money from a target host.
Hostname of the target server to analyze.
Amount of money you want to hack from the server.
The number of threads needed to hack the server for hackAmount money.
RAM cost: 1 GB
This function returns the decimal number of script threads you need when running the hack command to steal the specified amount of money from the target server. If hackAmount is less than zero or greater than the amount of money available on the server, then this function returns -1.
// Calculate threadcount of a single hack that would take $100k from n00dles
const hackThreads = hackAnalyzeThreads("n00dles", 1e5);
// Launching a script requires an integer thread count. The below would take less than the targeted $100k.
ns.run("noodleHack.js", Math.floor(hackThreads))
Check if you have root access on a server.
Hostname of the target server.
True if player has root access to the specified target server, and false otherwise.
RAM cost: 0.05 GB
Returns a boolean indicating whether or not the player has root access to the specified target server.
if (!ns.hasRootAccess("foodnstuff")) {
ns.nuke("foodnstuff");
}
Check if a script is running.
Filename or PID of script to check. This is case-sensitive.
Optional host: stringHostname of target server. Optional, defaults to the server the calling script is running on.
Rest ...args: ScriptArg[]Arguments to specify/identify the script. Optional, when looking for scripts run without arguments.
True if the specified script is running on the target server, and false otherwise.
RAM cost: 0.1 GB
Returns a boolean indicating whether the specified script is running on the target server. If you use a PID instead of a filename, the hostname and args parameters are unnecessary. If hostname is omitted while filename is used as the first parameter, hostname defaults to the server the calling script is running on. Remember that a script is semi-uniquely identified by both its name and its arguments. (You can run multiple copies of scripts with the same arguments, but for the purposes of functions like this that check based on filename, the filename plus arguments forms the key.)
//The function call will return true if there is a script named foo.js with no arguments running on the foodnstuff server, and false otherwise:
ns.isRunning("foo.js", "foodnstuff");
//The function call will return true if there is a script named foo.js with no arguments running on the current server, and false otherwise:
ns.isRunning("foo.js", ns.getHostname());
//The function call will return true if there is a script named foo.js running with the arguments 1, 5, and “test” (in that order) on the joesguns server, and false otherwise:
ns.isRunning("foo.js", "joesguns", 1, 5, "test");
Terminate the script with the provided PID.
The PID of the script to kill.
True if the script is successfully killed, and false otherwise.
RAM cost: 0.5 GB
Kills the script with the provided PID. To instead kill a script using its filename, hostname, and args, see NS.(kill:2) | the other ns.kill entry.
// kills the script with PID 20:
ns.kill(20);
Terminate the script(s) with the provided filename, hostname, and script arguments.
Filename of the script to kill.
Optional hostname: stringHostname where the script to kill is running. Defaults to the current server.
Rest ...args: ScriptArg[]Arguments of the script to kill.
True if the scripts were successfully killed, and false otherwise.
RAM cost: 0.5 GB
Kills the script(s) with the provided filename, running on the specified host with the specified args. To instead kill a script using its PID, see NS.(kill:1) | the other ns.kill entry.
// kill the script "foo.js" on the same server the current script is running from, with no arguments
ns.kill("foo.js");
// kill the script "foo.js" on the "n00dles" server with no arguments.
ns.kill("foo.js", "n00dles");
// kill the script foo.js on the current server that was run with the arguments [1, “foodnstuff”, false]:
ns.kill("foo.js", ns.getHostname(), 1, "foodnstuff", false);
Terminate all scripts on a server.
Optional host: stringIP or hostname of the server on which to kill all scripts.
Optional safetyguard: booleanSkips the script that calls this function
True if any scripts were killed, and false otherwise.
RAM cost: 0.5 GB
Kills all running scripts on the specified server. This function returns true if any scripts were killed, and false otherwise. In other words, it will return true if there are any scripts running on the target server. If no host is defined, it will kill all scripts, where the script is running.
List files on a server.
Hostname of the target server.
Optional substring: stringA substring to search for in the filename.
Array with the filenames of all files on the specified server.
RAM cost: 0.2 GB
Returns an array with the filenames of all files on the specified server (as strings). The returned array is sorted in alphabetic order.
Move a tail window.
x coordinate.
y coordinate.
Optional pid: numberOptional. PID of the script having its tail moved. If omitted, the current script is used.
RAM cost: 0 GB
Moves a tail window. Coordinates are in screenspace pixels (top left is 0,0).
Move a file on the target server.
Hostname of target server.
Filename of the source file.
Filename of the destination file.
RAM cost: 0 GB
Move the source file to the specified destination on the target server.
This command only works for scripts and text files (.txt). It cannot, however, be used to convert from script to text file, or vice versa.
This function can also be used to rename files.
Format a number using the numeral library. This function is deprecated and will be removed in 2.4.
Number to format.
Formatting options. See http://numeraljs.com/#format for valid formats.
Formatted number.
Use ns.formatNumber, formatRam, or formatPercent instead. Will be removed in 2.4.
RAM cost: 0 GB
Converts a number into a string with the specified format options. See http://numeraljs.com/#format for documentation on format strings supported.
This function is deprecated and will be removed in 2.3.
Runs NUKE.exe on a server.
Hostname of the target server.
RAM cost: 0.05 GB
Running NUKE.exe on a target server gives you root access which means you can execute scripts on said server. NUKE.exe must exist on your home computer.
ns.nuke("foodnstuff");
Get a copy of the data from a port without popping it.
Port to peek. Must be a positive integer.
Data in the specified port.
RAM cost: 0 GB
This function is used to peek at the data from a port. It returns the first element in the specified port without removing that element. If the port is empty, the string “NULL PORT DATA” will be returned.
Prints one or more values or variables to the script’s logs.
Rest ...args: any[]Value(s) to be printed.
RAM cost: 0 GB
If the argument is a string, you can color code your message by prefixing your string with one of these strings:
"ERROR": The whole string will be printed in red. Use this prefix to indicate
that an error has occurred.
"SUCCESS": The whole string will be printed in green, similar to the default
theme of the Terminal. Use this prefix to indicate that something is correct.
"WARN": The whole string will be printed in yellow. Use this prefix to
indicate that you or a user of your script should be careful of something.
"INFO": The whole string will be printed in purplish blue. Use this prefix to
remind yourself or a user of your script of something. Think of this prefix as
indicating an FYI (for your information).
For custom coloring, use ANSI escape sequences. The examples below use the Unicode
escape code \u001b. The color coding also works if \u001b is replaced with
the hexadecimal escape code \x1b. The Bash escape code \e is not supported.
The octal escape code \033 is not allowed because the game runs JavaScript in
strict mode.
// Default color coding.
ns.print("ERROR means something's wrong.");
ns.print("SUCCESS means everything's OK.");
ns.print("WARN Tread with caution!");
ns.print("WARNING, warning, danger, danger!");
ns.print("WARNing! Here be dragons.");
ns.print("INFO for your I's only (FYI).");
ns.print("INFOrmation overload!");
// Custom color coding.
const cyan = "\u001b[36m";
const green = "\u001b[32m";
const red = "\u001b[31m";
const reset = "\u001b[0m";
ns.print(`${red}Ugh! What a mess.${reset}`);
ns.print(`${green}Well done!${reset}`);
ns.print(`${cyan}ERROR Should this be in red?${reset}`);
ns.tail();
Prints a ReactNode to the script logs.
The React node to be printed.
Prints a formatted string to the script’s logs.
Format of the message.
Rest ...args: any[]Value(s) to be printed.
RAM cost: 0 GB
See print for how to add color to your printed strings.
For more detail, see: https://github.com/alexei/sprintf.js
const name = "Bit";
const age = 4;
ns.printf("My name is %s.", name);
ns.printf("I'm %d seconds old.", age);
ns.printf("My age in binary is %b.", age);
ns.printf("My age in scientific notation is %e.", age);
ns.printf("In %d seconds, I'll be %s.", 6, "Byte");
ns.printf("Am I a nibble? %t", (4 == age));
ns.tail();
Prompt the player with an input modal.
Text to appear in the prompt dialog box.
Optional options: { Options to modify the prompt the player is shown.
Optional choices?: string[]Optional type?: "boolean" | "text" | "select"True if the player clicks “Yes”; false if the player clicks “No”; or the value entered by the player.
RAM cost: 0 GB
Prompts the player with a dialog box and returns a promise. If the player cancels this dialog box (press X button or click outside the dialog box), the promise is resolved with a default value (empty string or "false"). If this API is called again while the old dialog box still exists, the old dialog box will be replaced with a new one, and the old promise will be resolved with the default value.
Here is an explanation of the various options.
options.type is not provided to the function. If options.type is left out and
only a string is passed to the function, then the default behavior is to create a
boolean dialog box.
options.type has value undefined or "boolean". A boolean dialog box is
created. The player is shown "Yes" and "No" prompts, which return true and false
respectively. The script's execution is halted until the player presses either the
"Yes" or "No" button.
options.type has value "text". The player is given a text field to enter
free-form text. The script's execution is halted until the player enters some text
and/or presses the "Confirm" button.
options.type has value "select". The player is shown a drop-down field.
Choosing type "select" will require an array to be passed via the
options.choices property. The array can be an array of strings, an array of
numbers (not BigInt numbers), or a mixture of both numbers and strings. Any other
types of array elements will result in an error or an undefined/unexpected
behavior. The options.choices property will be ignored if options.type has a
value other than "select". The script's execution is halted until the player
chooses one of the provided options and presses the "Confirm" button.
// A Yes/No question. The default is to create a boolean dialog box.
const queryA = "Do you enjoy Bitburner?";
const resultA = await ns.prompt(queryA);
ns.tprint(`${queryA} ${resultA}`);
// Another Yes/No question. Can also create a boolean dialog box by explicitly
// passing the option {"type": "boolean"}.
const queryB = "Is programming fun?";
const resultB = await ns.prompt(queryB, { type: "boolean" });
ns.tprint(`${queryB} ${resultB}`);
// Free-form text box.
const resultC = await ns.prompt("Please enter your name.", { type: "text" });
ns.tprint(`Hello, ${resultC}.`);
// A drop-down list.
const resultD = await ns.prompt("Please select your favorite fruit.", {
type: "select",
choices: ["Apple", "Banana", "Orange", "Pear", "Strawberry"]
});
ns.tprint(`Your favorite fruit is ${resultD.toLowerCase()}.`);
List running scripts on a server.
Optional host: stringHost address of the target server. If not specified, it will be the current server’s IP by default.
Array with general information about all scripts running on the specified target server.
RAM cost: 0.2 GB
Returns an array with general information about all scripts running on the specified target server.
const ps = ns.ps("home");
for (let script of ps) {
ns.tprint(`${script.filename} ${script.threads}`);
ns.tprint(script.args);
}
Purchase a server.
Hostname of the purchased server.
Amount of RAM of the purchased server, in GB. Must be a power of 2 (2, 4, 8, 16, etc.). Maximum value of 1048576 (2^20).
The hostname of the newly purchased server.
2.25 GB
Purchase a server with the specified hostname and amount of RAM.
The hostname argument can be any data type, but it will be converted to a string
and have whitespace removed. Anything that resolves to an empty string will cause
the function to fail. If there is already a server with the specified hostname,
then the function will automatically append a number at the end of the hostname
argument value until it finds a unique hostname. For example, if the script calls
purchaseServer(“foo”, 4) but a server named “foo” already exists, then it will
automatically change the hostname to foo-0. If there is already a server with the
hostname foo-0, then it will change the hostname to foo-1, and so on.
Note that there is a maximum limit to the amount of servers you can purchase.
Returns the hostname of the newly purchased server as a string. If the function fails to purchase a server, then it will return an empty string. The function will fail if the arguments passed in are invalid, if the player does not have enough money to purchase the specified server, or if the player has exceeded the maximum amount of servers.
// Attempt to purchase 5 servers with 64GB of ram each
const ram = 64;
const prefix = "pserv-";
for (i = 0; i < 5; ++i) {
ns.purchaseServer(prefix + i, ram);
}
Read content of a file.
Name of the file to be read.
Data in the specified text file.
RAM cost: 0 GB
This function is used to read data from a text file (.txt) or script (.js or .script).
This function will return the data in the specified file. If the file does not exist, an empty string will be returned.
Read data from a port.
Port to read from. Must be a positive integer.
The data read.
RAM cost: 0 GB
Read data from that port. A port is a serialized queue. This function will remove the first element from that queue and return it. If the queue is empty, then the string “NULL PORT DATA” will be returned.
Resize a tail window.
Width of the window.
Height of the window.
Optional pid: numberOptional. PID of the script having its tail resized. If omitted, the current script is used.
RAM cost: 0 GB
Resize a tail window. Size are in pixel.
Delete a file.
Filename of file to remove. Must include the extension.
Optional host: stringHostname of the server on which to delete the file. Optional. Defaults to current server.
True if it successfully deletes the file, and false otherwise.
RAM cost: 1 GB
Removes the specified file from the current server. This function works for every file type except message (.msg) files.
Start another script on the current server.
Filename of script to run.
Optional threadOrOptions: number | RunOptionsEither an integer number of threads for new script, or a RunOptions object. Threads defaults to 1.
Rest ...args: ScriptArg[]Additional arguments to pass into the new script that is being run. Note that if any arguments are being passed into the new script, then the second argument threadOrOptions must be filled in with a value.
Returns the PID of a successfully started script, and 0 otherwise.
RAM cost: 1 GB
Run a script as a separate process. This function can only be used to run scripts located on the current server (the server running the script that calls this function). Requires a significant amount of RAM to run this command.
The second argument is either a thread count, or a RunOptions object that can also specify the number of threads (among other things).
If the script was successfully started, then this functions returns the PID of that script. Otherwise, it returns 0.
PID stands for Process ID. The PID is a unique identifier for each script. The PID will always be a positive integer.
Running this function with 0 or fewer threads will cause a runtime error.
//The simplest way to use the run command is to call it with just the script name. The following example will run ‘foo.js’ single-threaded with no arguments:
ns.run("foo.js");
//The following example will run ‘foo.js’ but with 5 threads instead of single-threaded:
ns.run("foo.js", {threads: 5});
//This next example will run ‘foo.js’ single-threaded, and will pass the string ‘foodnstuff’ into the script as an argument:
ns.run("foo.js", 1, 'foodnstuff');
Get the list of servers connected to a server.
Optional host: stringOptional. Hostname of the server to scan, default to current server.
Returns an array of hostnames.
RAM cost: 0.2 GB
Returns an array containing the hostnames of all servers that are one node way from the specified target server. The hostnames in the returned array are strings.
// All servers that are one hop from the current server.
ns.tprint("Neighbors of current server.");
let neighbor = ns.scan();
for (let i = 0; i < neighbor.length; i++) {
ns.tprint(neighbor[i]);
}
// All neighbors of n00dles.
const target = "n00dles";
neighbor = ns.scan(target);
ns.tprintf("Neighbors of %s.", target);
for (let i = 0; i < neighbor.length; i++) {
ns.tprint(neighbor[i]);
}
Copy file between servers.
Filename or an array of filenames of script/literature files to copy. Note that if a file is located in a subdirectory, the filename must include the leading /.
Hostname of the destination server, which is the server to which the file will be copied.
Optional source: stringHostname of the source server, which is the server from which the file will be copied. This argument is optional and if it’s omitted the source will be the current server.
True if the file is successfully copied over and false otherwise. If the files argument is an array then this function will return false if any of the operations failed.
RAM cost: 0.6 GB
Copies a script or literature (.lit) file(s) to another server. The files argument can be either a string specifying a single file to copy, or an array of strings specifying multiple files to copy.
//Copies foo.lit from the helios server to the home computer:
ns.scp("foo.lit", "home", "helios" );
//Tries to copy three files from rothman-uni to home computer:
const files = ["foo1.lit", "foo2.txt", "foo3.js"];
ns.scp(files, "home", "rothman-uni");
const server = ns.args[0];
const files = ["hack.js", "weaken.js", "grow.js"];
ns.scp(files, server, "home");
Kill all scripts with a filename.
Filename of script to kill. This is case-sensitive.
Hostname of target server.
True if one or more scripts were successfully killed, and false if none were.
RAM cost: 1 GB
Kills all scripts with the specified filename on the target server specified by hostname, regardless of arguments.
Check if any script with a filename is running.
Filename of script to check. This is case-sensitive.
Hostname of target server.
True if the specified script is running, and false otherwise.
RAM cost: 1 GB
Returns a boolean indicating whether any instance of the specified script is running on the target server, regardless of its arguments.
This is different than the isRunning function because it does not try to identify a specific instance of a running script by its arguments.
//The function call will return true if there is any script named foo.js running on the foodnstuff server, and false otherwise:
ns.scriptRunning("foo.js", "foodnstuff");
//The function call will return true if there is any script named “foo.js” running on the current server, and false otherwise:
ns.scriptRunning("foo.js", ns.getHostname());
Set the title of the tail window of a script.
The new title for the tail window.
Optional pid: numberOptional. PID of the script having its tail closed. If omitted, the current script is used.
RAM cost: 0 GB
This sets the title to the given string, and also forces an update of the tail window's contents.
The title is saved across restarts, but only if it is a simple string.
If the pid is unspecified, it will modify the current script’s logs.
Otherwise, the pid argument can be used to change the logs from another script.
It is possible to pass any React Node instead of a string. See ReactElement and ReactNode types for additional info.
Suspends the script for n milliseconds.
Number of milliseconds to sleep.
A promise that resolves to true when the sleep is completed.
RAM cost: 0 GB
// This will count from 1 to 10 in your terminal, with one number every 5 seconds
for (var i = 1; i <= 10; i++) {
ns.tprint(i);
await ns.sleep(5000);
}
Terminate current script and start another in a defined number of milliseconds.
Filename of script to execute.
Optional threadOrOptions: number | SpawnOptionsEither an integer number of threads for new script, or a SpawnOptions object. Threads defaults to 1 and spawnDelay defaults to 10,000 ms.
Rest ...args: ScriptArg[]Additional arguments to pass into the new script that is being run.
RAM cost: 2 GB
Terminates the current script, and then after a defined delay it will execute the newly-specified script. The purpose of this function is to execute a new script without being constrained by the RAM usage of the current one. This function can only be used to run scripts on the local server.
Because this function immediately terminates the script, it does not have a return value.
Running this function with 0 or fewer threads will cause a runtime error.
//The following example will execute the script ‘foo.js’ with 10 threads, in 500 milliseconds and the arguments ‘foodnstuff’ and 90:
ns.spawn('foo.js', {threads: 10, spawnDelay: 500}, 'foodnstuff', 90);
Open the tail window of a script.
Optional fn: FilenameOrPIDOptional. Filename or PID of the script being tailed. If omitted, the current script is tailed.
Optional host: stringOptional. Hostname of the script being tailed. Defaults to the server this script is running on. If args are specified, this is not optional.
Rest ...args: ScriptArg[]Arguments for the script being tailed.
RAM cost: 0 GB
Opens a script’s logs. This is functionally the same as the tail Terminal command.
If the function is called with no arguments, it will open the current script’s logs.
Otherwise, the PID or filename, hostname/ip, and args… arguments can be used to get the logs from another script. Remember that scripts are uniquely identified by both their names and arguments.
//Open logs from foo.js on the current server that was run with no args
ns.tail("foo.js");
//Get logs from foo.js on the foodnstuff server that was run with no args
ns.tail("foo.js", "foodnstuff");
//Get logs from foo.js on the foodnstuff server that was run with the arguments [1, "test"]
ns.tail("foo.js", "foodnstuff", 1, "test");
Queue a toast (bottom-right notification).
Message in the toast.
Optional variant: ToastVariant | "success" | "warning" | "error" | "info"Type of toast. Must be one of success, info, warning, error. Defaults to success.
Optional duration: null | numberDuration of toast in ms. Can also be null to create a persistent toast. Defaults to 2000.
Prints a ReactNode to the terminal.
The React node to be printed.
Prints a raw value or a variable to the Terminal.
Format of the message.
Rest ...values: any[]Value(s) to be printed.
RAM cost: 0 GB
See print for how to add color to your printed strings.
See printf for examples on formatted strings.
For more detail, see: https://github.com/alexei/sprintf.js
Attempt to write to a port.
Port to attempt to write to. Must be a positive integer.
Data to write, it's cloned with structuredClone().
True if the data is successfully written to the port, and false otherwise.
RAM cost: 0 GB
Attempts to write data to the specified Netscript port. If the port is full, the data will not be written. Otherwise, the data will be written normally.
Upgrade a purchased server's RAM.
Hostname of the server to upgrade.
Amount of RAM of the purchased server, in GB. Must be a power of 2 (2, 4, 8, 16, etc.). Maximum value of 1048576 (2^20).
True if the upgrade succeeded, and false otherwise.
RAM cost: 0.25 GB
Reduce a server's security level.
Hostname of the target server to weaken.
Optional opts: BasicHGWOptionsOptional parameters for configuring function behavior.
A promise that resolves to the value by which security was reduced.
RAM cost: 0.15 GB
Use your hacking skills to attack a server’s security, lowering the server’s security level. The runtime for this function depends on your hacking level and the target server’s security level when this function is called. This function lowers the security level of the target server by 0.05.
Like hack and grow, weaken can be called on any server, regardless of
where the script is running. This function requires root access to the target server, but
there is no required hacking level to run the function.
let currentSecurity = ns.getServerSecurityLevel("foodnstuff");
currentSecurity -= await ns.weaken("foodnstuff");
Predict the effect of weaken.
Amount of threads that will be used.
Optional cores: numberOptional. The number of cores of the server that would run weaken.
The security decrease.
RAM cost: 1 GB
Returns the security decrease that would occur if a weaken with this many threads happened.
Download a file from the internet.
URL to pull data from.
Filename to write data to. Must be script or text file.
Optional host: stringOptional hostname/ip of server for target file.
True if the data was successfully retrieved from the URL, false otherwise.
RAM cost: 0 GB
Retrieves data from a URL and downloads it to a file on the specified server. The data can only be downloaded to a script (.js or .script) or a text file (.txt). If the file already exists, it will be overwritten by this command. Note that it will not be possible to download data from many websites because they do not allow cross-origin resource sharing (CORS).
IMPORTANT: This is an asynchronous function that returns a Promise. The Promise’s resolved value will be a boolean indicating whether or not the data was successfully retrieved from the URL. Because the function is async and returns a Promise, it is recommended you use wget in NetscriptJS (Netscript 2.0).
In NetscriptJS, you must preface any call to wget with the await keyword (like you would hack or sleep). wget will still work in Netscript 1.0, but the function's execution will not be synchronous (i.e. it may not execute when you expect/want it to). Furthermore, since Promises are not supported in ES5, you will not be able to process the returned value of wget in Netscript 1.0.
await ns.wget("https://raw.githubusercontent.com/bitburner-official/bitburner-src/master/README.md", "game_readme.txt");
Write data to a file.
Name of the file to be written to.
Optional data: stringData to write.
Optional mode: "w" | "a"Defines the write mode.
RAM cost: 0 GB
This function can be used to write data to a text file (.txt) or a script (.js or .script).
This function will write data to that file. If the specified file does not exist, then it will be created. The third argument mode defines how the data will be written to the file. If mode is set to “w”, then the data is written in “write” mode which means that it will overwrite all existing data on the file. If mode is set to any other value then the data will be written in “append” mode which means that the data will be added at the end of the file.
Write data to a port.
Port to write to. Must be a positive integer.
Data to write, it's cloned with structuredClone().
The data popped off the queue if it was full, or null if it was not full.
RAM cost: 0 GB
Write data to the given Netscript port.
Collection of all functions passed to scripts
Remarks
Basic usage example: