Interface NS

Collection of all functions passed to scripts

Remarks

Basic usage example:

export async function main(ns) {
// Basic ns functions can be accessed on the ns object
ns.getHostname();
// Some related functions are gathered under a sub-property of the ns object
ns.stock.getPrice();
// Most functions that return a promise need to be awaited.
await ns.hack('n00dles');
}
interface NS {
    args: ScriptArg[];
    bladeburner: Bladeburner;
    codingcontract: CodingContract;
    corporation: Corporation;
    enums: NSEnums;
    formulas: Formulas;
    gang: Gang;
    go: Go;
    grafting: Grafting;
    hacknet: Hacknet;
    heart: {
        break(): number;
    };
    infiltration: Infiltration;
    pid: number;
    singularity: Singularity;
    sleeve: Sleeve;
    stanek: Stanek;
    stock: TIX;
    ui: UserInterface;
    alert(msg): void;
    asleep(millis): Promise<true>;
    atExit(f, id?): void;
    brutessh(host): void;
    clear(handle): void;
    clearLog(): void;
    clearPort(portNumber): void;
    closeTail(pid?): void;
    deleteServer(host): boolean;
    disableLog(fn): void;
    enableLog(fn): void;
    exec(script, hostname, threadOrOptions?, ...args): number;
    exit(): never;
    fileExists(filename, host?): boolean;
    flags(schema): {
        [key: string]: ScriptArg | string[];
    };
    formatNumber(n, fractionalDigits?, suffixStart?, isInteger?): string;
    formatPercent(n, fractionalDigits?, suffixStart?): string;
    formatRam(n, fractionalDigits?): string;
    ftpcrack(host): void;
    getBitNodeMultipliers(n?, lvl?): BitNodeMultipliers;
    getFavorToDonate(): number;
    getFunctionRamCost(name): number;
    getGrowTime(host): number;
    getHackTime(host): number;
    getHackingLevel(): number;
    getHackingMultipliers(): HackingMultipliers;
    getHacknetMultipliers(): HacknetMultipliers;
    getHostname(): string;
    getMoneySources(): MoneySources;
    getPlayer(): Player;
    getPortHandle(portNumber): NetscriptPort;
    getPurchasedServerCost(ram): number;
    getPurchasedServerLimit(): number;
    getPurchasedServerMaxRam(): number;
    getPurchasedServerUpgradeCost(hostname, ram): number;
    getPurchasedServers(): string[];
    getRecentScripts(): RecentScript[];
    getResetInfo(): ResetInfo;
    getRunningScript(filename?, hostname?, ...args): null | RunningScript;
    getScriptExpGain(script, host, ...args): number;
    getScriptIncome(script, host, ...args): number;
    getScriptLogs(fn?, host?, ...args): string[];
    getScriptName(): string;
    getScriptRam(script, host?): number;
    getServer(host?): Server;
    getServerBaseSecurityLevel(host): number;
    getServerGrowth(host): number;
    getServerMaxMoney(host): number;
    getServerMaxRam(host): number;
    getServerMinSecurityLevel(host): number;
    getServerMoneyAvailable(host): number;
    getServerNumPortsRequired(host): number;
    getServerRequiredHackingLevel(host): number;
    getServerSecurityLevel(host): number;
    getServerUsedRam(host): number;
    getSharePower(): number;
    getTimeSinceLastAug(): number;
    getTotalScriptExpGain(): number;
    getTotalScriptIncome(): [number, number];
    getWeakenTime(host): number;
    grow(host, opts?): Promise<number>;
    growthAnalyze(host, multiplier, cores?): number;
    growthAnalyzeSecurity(threads, hostname?, cores?): number;
    hack(host, opts?): Promise<number>;
    hackAnalyze(host): number;
    hackAnalyzeChance(host): number;
    hackAnalyzeSecurity(threads, hostname?): number;
    hackAnalyzeThreads(host, hackAmount): number;
    hasRootAccess(host): boolean;
    hasTorRouter(): boolean;
    httpworm(host): void;
    isLogEnabled(fn): boolean;
    isRunning(script, host?, ...args): boolean;
    kill(pid): boolean;
    kill(filename, hostname?, ...args): boolean;
    killall(host?, safetyguard?): boolean;
    ls(host, substring?): string[];
    moveTail(x, y, pid?): void;
    mv(host, source, destination): void;
    nFormat(n, format): string;
    nextPortWrite(port): Promise<void>;
    nuke(host): void;
    peek(portNumber): any;
    print(...args): void;
    printRaw(node): void;
    printf(format, ...args): void;
    prompt(txt, options?): Promise<string | boolean>;
    ps(host?): ProcessInfo[];
    purchaseServer(hostname, ram): string;
    read(filename): string;
    readPort(portNumber): any;
    relaysmtp(host): void;
    renamePurchasedServer(hostname, newName): boolean;
    resizeTail(width, height, pid?): void;
    rm(name, host?): boolean;
    run(script, threadOrOptions?, ...args): number;
    scan(host?): string[];
    scp(files, destination, source?): boolean;
    scriptKill(script, host): boolean;
    scriptRunning(script, host): boolean;
    serverExists(host): boolean;
    setTitle(title, pid?): void;
    share(): Promise<void>;
    sleep(millis): Promise<true>;
    spawn(script, threadOrOptions?, ...args): void;
    sprintf(format, ...args): string;
    sqlinject(host): void;
    tFormat(milliseconds, milliPrecision?): string;
    tail(fn?, host?, ...args): void;
    toast(msg, variant?, duration?): void;
    tprint(...args): void;
    tprintRaw(node): void;
    tprintf(format, ...values): void;
    tryWritePort(portNumber, data): boolean;
    upgradePurchasedServer(hostname, ram): boolean;
    vsprintf(format, args): string;
    weaken(host, opts?): Promise<number>;
    weakenAnalyze(threads, cores?): number;
    wget(url, target, host?): Promise<boolean>;
    write(filename, data?, mode?): void;
    writePort(portNumber, data): any;
}

Properties

Methods

Properties

args: ScriptArg[]

Arguments passed into the script.

Remarks

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.

Example

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
}
bladeburner: Bladeburner

Namespace for bladeburner functions. Contains spoilers.

Remarks

RAM cost: 0 GB

codingcontract: CodingContract

Namespace for codingcontract functions.

Remarks

RAM cost: 0 GB

corporation: Corporation

Namespace for corporation functions. Contains spoilers.

Remarks

RAM cost: 0 GB

enums: NSEnums
formulas: Formulas

Namespace for formulas functions.

Remarks

RAM cost: 0 GB

gang: Gang

Namespace for gang functions. Contains spoilers.

Remarks

RAM cost: 0 GB

go: Go

Namespace for Go functions.

Remarks

RAM cost: 0 GB

grafting: Grafting

Namespace for grafting functions. Contains spoilers.

Remarks

RAM cost: 0 GB

hacknet: Hacknet

Namespace for hacknet functions. Some of this API contains spoilers.

Remarks

RAM cost: 4 GB.

heart: {
    break(): number;
}

Type declaration

infiltration: Infiltration

Namespace for infiltration functions.

Remarks

RAM cost: 0 GB

pid: number

The current script's PID

singularity: Singularity

Namespace for singularity functions. Contains spoilers.

Remarks

RAM cost: 0 GB

sleeve: Sleeve

Namespace for sleeve functions. Contains spoilers.

Remarks

RAM cost: 0 GB

stanek: Stanek

Namespace for stanek functions. Contains spoilers.

Remarks

RAM cost: 0 GB

stock: TIX

Namespace for stock functions.

Remarks

RAM cost: 0 GB

Namespace for user interface functions.

Remarks

RAM cost: 0 GB

Methods

  • Suspends the script for n milliseconds. Doesn't block with concurrent calls.

    Parameters

    • millis: number

      Number of milliseconds to sleep.

    Returns Promise<true>

    A promise that resolves to true when the sleep is completed.

    Remarks

    RAM cost: 0 GB

  • Add callback function when the script dies

    Parameters

    • f: (() => void)
        • (): void
        • Returns void

    • Optional id: string

    Returns void

    Remarks

    RAM cost: 0 GB

    NS2 exclusive

    Add callback to be executed when the script dies.

  • Runs BruteSSH.exe on a server.

    Parameters

    • host: string

      Hostname of the target server.

    Returns void

    Remarks

    RAM cost: 0.05 GB

    Runs the BruteSSH.exe program on the target server. BruteSSH.exe must exist on your home computer.

    Example

    ns.brutessh("foodnstuff");
    
  • Clear data from a file.

    Parameters

    • handle: string

      Text file to clear.

    Returns void

    Remarks

    RAM cost: 0 GB

    Delete all data from that text file.

  • Clear data from a port.

    Parameters

    • portNumber: number

      Port to clear data from. Must be a positive integer.

    Returns void

    Remarks

    RAM cost: 0 GB

    Delete all data from the underlying queue.

  • Close the tail window of a script.

    Parameters

    • Optional pid: number

      Optional. PID of the script having its tail closed. If omitted, the current script is used.

    Returns void

    Remarks

    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.

    Parameters

    • host: string

      Hostname of the server to delete.

    Returns boolean

    True if successful, and false otherwise.

    Remarks

    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.

    Parameters

    • fn: string

      Name of function for which to disable logging.

    Returns void

    Remarks

    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.

    Parameters

    • fn: string

      Name of function for which to enable logging.

    Returns void

    Remarks

    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.

    Parameters

    • script: string

      Filename of script to execute. This file must already exist on the target server.

    • hostname: string

      Hostname of the target server on which to execute the script.

    • Optional threadOrOptions: number | RunOptions

      Either 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 number

    Returns the PID of a successfully started script, and 0 otherwise.

    Remarks

    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.

    Example

    // 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.

    Parameters

    • filename: string

      Filename of file to check.

    • Optional host: string

      Host of target server. Optional, defaults to the server the script is running on.

    Returns boolean

    True if specified file exists, and false otherwise.

    Remarks

    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'.

    Example

    // 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.

    Parameters

    • schema: [string, string | number | boolean | string[]][]

    Returns {
        [key: string]: ScriptArg | string[];
    }

    Remarks

    RAM cost: 0 GB

    Allows Unix-like flag parsing.

    Example

    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.

    Parameters

    • n: number

      Number to format.

    • Optional fractionalDigits: number

      Number of digits to show in the fractional part of the decimal number. Optional, defaults to 3.

    • Optional suffixStart: number

      How high a number must be before a suffix will be added. Optional, defaults to 1000.

    • Optional isInteger: boolean

      Whether the number represents an integer. Integers do not display fractional digits until a suffix is present. Optional, defaults to false.

    Returns string

    Formatted number.

    Remarks

    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.

    Parameters

    • n: number

      Number to format as a percentage.

    • Optional fractionalDigits: number

      Number of digits to show in the fractional part of the decimal number. Optional, defaults to 2.

    • Optional suffixStart: number

      When to switch the percentage to a multiplier. Default is 1e6 or x1.00m.

    Returns string

    Formatted percentage.

    Remarks

    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.

    Parameters

    • n: number

      Number to format as an amount of ram, in base units of GB (or GiB if that Numeric Display option is set).

    • Optional fractionalDigits: number

      Number of digits to show in the fractional part of the decimal number. Optional, defaults to 2.

    Returns string

    Formatted ram amount.

    Remarks

    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

  • Runs FTPCrack.exe on a server.

    Parameters

    • host: string

      Hostname of the target server.

    Returns void

    Remarks

    RAM cost: 0.05 GB

    Runs the FTPCrack.exe program on the target server. FTPCrack.exe must exist on your home computer.

    Example

    ns.ftpcrack("foodnstuff");
    
  • Get the current Bitnode multipliers.

    Parameters

    • Optional n: number
    • Optional lvl: number

    Returns BitNodeMultipliers

    Object containing the current BitNode multipliers.

    Remarks

    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.

    Example

    const mults = ns.getBitNodeMultipliers();
    ns.tprint(`ServerMaxMoney: ${mults.ServerMaxMoney}`);
    ns.tprint(`HackExpGain: ${mults.HackExpGain}`);
  • Returns the amount of Faction favor required to be able to donate to a faction.

    Returns number

    Amount of Faction favor required to be able to donate to a faction.

    Remarks

    RAM cost: 0.1 GB

  • Get the ram cost of a netscript function.

    Parameters

    • name: string

      The fully-qualified function name, without the leading ns. Example inputs: hack, tprint, stock.getPosition.

    Returns number

    Remarks

    RAM cost: 0 GB

  • Get the execution time of a grow() call.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    Returns the amount of time in milliseconds it takes to execute the grow Netscript function.

    Remarks

    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.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    Returns the amount of time in milliseconds it takes to execute the hack Netscript function.

    Remarks

    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.

  • Returns the player’s current hacking level.

    Returns number

    Player’s current hacking level

    Remarks

    RAM cost: 0.05 GB

  • Get hacking related multipliers.

    Returns HackingMultipliers

    Object containing the Player’s hacking related multipliers.

    Remarks

    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%).

    Example

    const mults = ns.getHackingMultipliers();
    print(`chance: ${mults.chance}`);
    print(`growth: ${mults.growth}`);
  • Get hacknet related multipliers.

    Returns HacknetMultipliers

    Object containing the Player’s hacknet related multipliers.

    Remarks

    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%).

    Example

    const mults = ns.getHacknetMultipliers();
    ns.tprint(`production: ${mults.production}`);
    ns.tprint(`purchaseCost: ${mults.purchaseCost}`);
  • Returns a string with the hostname of the server that the script is running on.

    Returns string

    Hostname of the server that the script runs on.

    Remarks

    RAM cost: 0.05 GB

  • Get all data on a port.

    Parameters

    • portNumber: number

      Port number. Must be a positive integer.

    Returns NetscriptPort

    Remarks

    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.

    Parameters

    • ram: number

      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).

    Returns number

    The cost to purchase a server with the specified amount of ram.

    Remarks

    RAM cost: 0.25 GB

    Returns the cost to purchase a server with the specified amount of ram.

    Example

    const ram = 2 ** 20;
    const cost = ns.getPurchasedServerCost(ram);
    ns.tprint(`A purchased server with ${ns.formatRam(ram)} costs ${ns.formatMoney(cost)}`);
  • Returns the maximum number of servers you can purchase.

    Returns number

    Returns the maximum number of servers you can purchase.

    Remarks

    RAM cost: 0.05 GB

  • Returns the maximum RAM that a purchased server can have.

    Returns number

    Returns the maximum RAM (in GB) that a purchased server can have.

    Remarks

    RAM cost: 0.05 GB

  • Get cost of upgrading a purchased server to the given ram.

    Parameters

    • hostname: string

      Hostname of the server to upgrade.

    • ram: number

      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).

    Returns number

    The price to upgrade.

    Remarks

    RAM cost: 0.1 GB

  • Returns an array with the hostnames of all of the servers you have purchased.

    Returns string[]

    Returns an array with the hostnames of all of the servers you have purchased.

    Remarks

    2.25 GB

  • Get an array of recently killed scripts across all servers.

    Returns RecentScript[]

    Array with information about previously killed scripts.

    Remarks

    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.

    Example

    let recentScripts = ns.getRecentScripts();
    let mostRecent = recentScripts.shift()
    if (mostRecent)
    ns.tprint(mostRecent.logs.join('\n'))
  • Get information about resets.

    Returns ResetInfo

    Remarks

    RAM cost: 1 GB

    Example

    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.

    Parameters

    • Optional filename: FilenameOrPID

      Optional. Filename or PID of the script.

    • Optional hostname: string

      Hostname 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.

    Returns null | RunningScript

    The info about the running script if found, and null otherwise.

    Remarks

    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.

    Parameters

    • script: string

      Filename of script.

    • host: string

      Server on which script is running.

    • Rest ...args: ScriptArg[]

      Arguments that the script is running with.

    Returns number

    Amount of hacking experience the specified script generates while online.

    Remarks

    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.

    Parameters

    • script: string

      Filename of script.

    • host: string

      Server on which script is running.

    • Rest ...args: ScriptArg[]

      Arguments that the script is running with.

    Returns number

    Amount of income the specified script generates while online.

    Remarks

    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.

    Parameters

    • Optional fn: FilenameOrPID

      Optional. Filename or PID of script to get logs from.

    • Optional host: string

      Optional. Hostname of the server that the script is on.

    • Rest ...args: ScriptArg[]

      Arguments to identify which scripts to get logs for.

    Returns string[]

    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.

    Remarks

    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.

    Example

    //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");
  • Returns the current script name.

    Returns string

    Current script name.

    Remarks

    RAM cost: 0 GB

  • Get the ram cost of a script.

    Parameters

    • script: string

      Filename of script. This is case-sensitive.

    • Optional host: string

      Hostname 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.

    Returns number

    Amount of RAM (in GB) required to run the specified script on the target server, and 0 if the script does not exist.

    Remarks

    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.

  • Returns a server object for the given server. Defaults to the running script's server if host is not specified.

    Parameters

    • Optional host: string

      Optional. Hostname for the requested server object.

    Returns Server

    The requested server object.

    Remarks

    RAM cost: 2 GB

  • Get the base security level of a server.

    Parameters

    • host: string

      Host of target server.

    Returns number

    Base security level of the target server.

    Remarks

    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.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    Parameter that affects the percentage by which the server’s money is increased when using the grow function.

    Remarks

    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 the maximum money available on a server.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    Maximum amount of money available on the server.

    Remarks

    RAM cost: 0.1 GB

    Returns the maximum amount of money that can be available on a server.

  • Get the maximum amount of RAM on a server.

    Parameters

    • host: string

      Hostname of the target server.

    Returns number

    The maximum amount of RAM (GB) a server can have.

    Remarks

    RAM cost: 0.05 GB

  • Returns the minimum security level of the target server.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    Minimum security level of the target server.

    Remarks

    RAM cost: 0.1 GB

  • Get money available on a server.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    Amount of money available on the server.

    Remarks

    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.

    Example

    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.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    The number of open ports required to successfully run NUKE.exe on the specified server.

    Remarks

    RAM cost: 0.1 GB

  • Returns the required hacking level of the target server.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    The required hacking level of the target server.

    Remarks

    RAM cost: 0.1 GB

  • Get server security level.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    Security level of the target server.

    Remarks

    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 used RAM on a server.

    Parameters

    • host: string

      Hostname of the target server.

    Returns number

    The amount of used RAM (GB) on the specified server.

    Remarks

    RAM cost: 0.05 GB

  • Share Power has a multiplicative effect on rep/second while doing work for a faction. Share Power increases incrementally for every thread of share running on your server network, but at a sharply decreasing rate.

    Returns number

    Remarks

    RAM cost: 0.2 GB

  • Returns the amount of time in milliseconds that have passed since you last installed Augmentations.

    Returns number

    Time in milliseconds that have passed since you last installed Augmentations.

    Remarks

    RAM cost: 0.05 GB

  • Get the exp gain of all scripts.

    Returns number

    Total experience gain rate of all of your active scripts.

    Remarks

    RAM cost: 0.1 GB

  • Get the income of all scripts.

    Returns [number, number]

    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.

    Remarks

    RAM cost: 0.1 GB

  • Get the execution time of a weaken() call.

    Parameters

    • host: string

      Hostname of target server.

    Returns number

    Returns the amount of time in milliseconds it takes to execute the weaken Netscript function.

    Remarks

    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.

    Parameters

    • host: string

      Hostname of the target server to grow.

    • Optional opts: BasicHGWOptions

      Optional parameters for configuring function behavior.

    Returns Promise<number>

    The total effective multiplier that was applied to the server's money (after both additive and multiplicative growth).

    Remarks

    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.

    Example

    let currentMoney = ns.getServerMoneyAvailable("n00dles");
    currentMoney *= await ns.grow("foodnstuff");
  • Calculate the number of grow threads needed for a given multiplicative growth factor.

    Parameters

    • host: string

      Hostname of the target server.

    • multiplier: number

      Multiplier that will be applied to a server's money after applying additive growth. Decimal form.

    • Optional cores: number

      Number of cores on the host running the grow function. Optional, defaults to 1.

    Returns number

    Decimal number of grow threads needed for the specified multiplicative growth factor (does not include additive growth).

    Remarks

    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.

    Example

    // 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.

    Parameters

    • threads: number

      Amount of threads that will be used.

    • Optional hostname: string

      Optional. Hostname of the target server. If provided, security increase is limited by the number of threads needed to reach maximum money.

    • Optional cores: number

      Optional. The number of cores of the server that would run grow.

    Returns number

    The security increase.

    Remarks

    RAM cost: 1 GB

    Returns the security increase that would occur if a grow with this many threads happened.

  • Steal a server's money.

    Parameters

    • host: string

      Hostname of the target server to hack.

    • Optional opts: BasicHGWOptions

      Optional parameters for configuring function behavior.

    Returns Promise<number>

    A promise that resolves to the amount of money stolen (which is zero if the hack is unsuccessful).

    Remarks

    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.

    Example

    let earnedMoney = await ns.hack("foodnstuff");
    
  • Get the part of money stolen with a single thread.

    Parameters

    • host: string

      Hostname of the target server.

    Returns number

    The part of money you will steal from the target server with a single thread hack.

    Remarks

    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.

    Example

    //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.

    Parameters

    • host: string

      Hostname of the target server.

    Returns number

    The chance you have of successfully hacking the target server.

    Remarks

    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.

    Parameters

    • threads: number

      Amount of threads that will be used.

    • Optional hostname: string

      Hostname of the target server. The number of threads is limited to the number needed to hack the server's maximum amount of money.

    Returns number

    The security increase.

    Remarks

    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.

    Parameters

    • host: string

      Hostname of the target server to analyze.

    • hackAmount: number

      Amount of money you want to hack from the server.

    Returns number

    The number of threads needed to hack the server for hackAmount money.

    Remarks

    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.

    Example

    // 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.

    Parameters

    • host: string

      Hostname of the target server.

    Returns boolean

    True if player has root access to the specified target server, and false otherwise.

    Remarks

    RAM cost: 0.05 GB

    Returns a boolean indicating whether or not the player has root access to the specified target server.

    Example

    if (!ns.hasRootAccess("foodnstuff")) {
    ns.nuke("foodnstuff");
    }
  • Returns whether the player has access to the darkweb.

    Returns boolean

    Whether player has access to the dark web.

    Remarks

    RAM cost: 0.05GB

    Example

    if (ns.hasTorRouter()) ns.tprint("TOR router detected.");
    
  • Runs HTTPWorm.exe on a server.

    Parameters

    • host: string

      Hostname of the target server.

    Returns void

    Remarks

    RAM cost: 0.05 GB

    Runs the HTTPWorm.exe program on the target server. HTTPWorm.exe must exist on your home computer.

    Example

    ns.httpworm("foodnstuff");
    
  • Checks the status of the logging for the given function.

    Parameters

    • fn: string

      Name of function to check.

    Returns boolean

    Returns a boolean indicating whether or not logging is enabled for that function (or ALL).

    Remarks

    RAM cost: 0 GB

  • Check if a script is running.

    Parameters

    • script: FilenameOrPID

      Filename or PID of script to check. This is case-sensitive.

    • Optional host: string

      Hostname 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.

    Returns boolean

    True if the specified script is running on the target server, and false otherwise.

    Remarks

    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.)

    Example

    //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.

    Parameters

    • pid: number

      The PID of the script to kill.

    Returns boolean

    True if the script is successfully killed, and false otherwise.

    Remarks

    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.

    Example

    // kills the script with PID 20:
    ns.kill(20);
  • Terminate the script(s) with the provided filename, hostname, and script arguments.

    Parameters

    • filename: string

      Filename of the script to kill.

    • Optional hostname: string

      Hostname where the script to kill is running. Defaults to the current server.

    • Rest ...args: ScriptArg[]

      Arguments of the script to kill.

    Returns boolean

    True if the scripts were successfully killed, and false otherwise.

    Remarks

    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.

    Example

    // 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.

    Parameters

    • Optional host: string

      IP or hostname of the server on which to kill all scripts.

    • Optional safetyguard: boolean

      Skips the script that calls this function

    Returns boolean

    True if any scripts were killed, and false otherwise.

    Remarks

    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.

    Parameters

    • host: string

      Hostname of the target server.

    • Optional substring: string

      A substring to search for in the filename.

    Returns string[]

    Array with the filenames of all files on the specified server.

    Remarks

    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.

    Parameters

    • x: number

      x coordinate.

    • y: number

      y coordinate.

    • Optional pid: number

      Optional. PID of the script having its tail moved. If omitted, the current script is used.

    Returns void

    Remarks

    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.

    Parameters

    • host: string

      Hostname of target server.

    • source: string

      Filename of the source file.

    • destination: string

      Filename of the destination file.

    Returns void

    Remarks

    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.

    Parameters

    Returns string

    Formatted number.

    Deprecated

    Use ns.formatNumber, formatRam, or formatPercent instead. Will be removed in 2.4.

    Remarks

    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.

  • Listen for a port write.

    Parameters

    • port: number

      Port to listen for a write on. Must be a positive integer.

    Returns Promise<void>

    Remarks

    RAM cost: 0 GB

    Sleeps until the port is written to.

  • Runs NUKE.exe on a server.

    Parameters

    • host: string

      Hostname of the target server.

    Returns void

    Remarks

    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.

    Example

    ns.nuke("foodnstuff");
    
  • Get a copy of the data from a port without popping it.

    Parameters

    • portNumber: number

      Port to peek. Must be a positive integer.

    Returns any

    Data in the specified port.

    Remarks

    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.

    Parameters

    • Rest ...args: any[]

      Value(s) to be printed.

    Returns void

    Remarks

    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.

    Example

    // 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 formatted string to the script’s logs.

    Parameters

    • format: string

      Format of the message.

    • Rest ...args: any[]

      Value(s) to be printed.

    Returns void

    Remarks

    RAM cost: 0 GB

    Example

    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.

    Parameters

    • txt: string

      Text to appear in the prompt dialog box.

    • Optional options: {
          choices?: string[];
          type?: "boolean" | "text" | "select";
      }

      Options to modify the prompt the player is shown.

      • Optional choices?: string[]
      • Optional type?: "boolean" | "text" | "select"

    Returns Promise<string | boolean>

    True if the player clicks “Yes”; false if the player clicks “No”; or the value entered by the player.

    Remarks

    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.

    Example

    // 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.

    Parameters

    • Optional host: string

      Host address of the target server. If not specified, it will be the current server’s IP by default.

    Returns ProcessInfo[]

    Array with general information about all scripts running on the specified target server.

    Remarks

    RAM cost: 0.2 GB

    Returns an array with general information about all scripts running on the specified target server.

    Example

    const ps = ns.ps("home");
    for (let script of ps) {
    ns.tprint(`${script.filename} ${script.threads}`);
    ns.tprint(script.args);
    }
  • Purchase a server.

    Parameters

    • hostname: string

      Hostname of the purchased server.

    • ram: number

      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).

    Returns string

    The hostname of the newly purchased server.

    Remarks

    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.

    Example

    // 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.

    Parameters

    • filename: string

      Name of the file to be read.

    Returns string

    Data in the specified text file.

    Remarks

    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.

    Parameters

    • portNumber: number

      Port to read from. Must be a positive integer.

    Returns any

    The data read.

    Remarks

    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.

  • Runs relaySMTP.exe on a server.

    Parameters

    • host: string

      Hostname of the target server.

    Returns void

    Remarks

    RAM cost: 0.05 GB

    Runs the relaySMTP.exe program on the target server. relaySMTP.exe must exist on your home computer.

    Example

    ns.relaysmtp("foodnstuff");
    
  • Rename a purchased server.

    Parameters

    • hostname: string

      Current server hostname.

    • newName: string

      New server hostname.

    Returns boolean

    True if successful, and false otherwise.

    Remarks

    RAM cost: 0 GB

  • Resize a tail window.

    Parameters

    • width: number

      Width of the window.

    • height: number

      Height of the window.

    • Optional pid: number

      Optional. PID of the script having its tail resized. If omitted, the current script is used.

    Returns void

    Remarks

    RAM cost: 0 GB

    Resize a tail window. Size are in pixel.

  • Delete a file.

    Parameters

    • name: string

      Filename of file to remove. Must include the extension.

    • Optional host: string

      Hostname of the server on which to delete the file. Optional. Defaults to current server.

    Returns boolean

    True if it successfully deletes the file, and false otherwise.

    Remarks

    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.

    Parameters

    • script: string

      Filename of script to run.

    • Optional threadOrOptions: number | RunOptions

      Either 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 number

    Returns the PID of a successfully started script, and 0 otherwise.

    Remarks

    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.

    Example

    //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.

    Parameters

    • Optional host: string

      Optional. Hostname of the server to scan, default to current server.

    Returns string[]

    Returns an array of hostnames.

    Remarks

    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.

    Example

    // 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.

    Parameters

    • files: string | string[]

      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 /.

    • destination: string

      Hostname of the destination server, which is the server to which the file will be copied.

    • Optional source: string

      Hostname 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.

    Returns boolean

    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.

    Remarks

    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.

    Example

    //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");

    Example

    const server = ns.args[0];
    const files = ["hack.js", "weaken.js", "grow.js"];
    ns.scp(files, server, "home");
  • Kill all scripts with a filename.

    Parameters

    • script: string

      Filename of script to kill. This is case-sensitive.

    • host: string

      Hostname of target server.

    Returns boolean

    True if one or more scripts were successfully killed, and false if none were.

    Remarks

    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.

    Parameters

    • script: string

      Filename of script to check. This is case-sensitive.

    • host: string

      Hostname of target server.

    Returns boolean

    True if the specified script is running, and false otherwise.

    Remarks

    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.

    Example

    //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());
  • Returns a boolean denoting whether or not the specified server exists.

    Parameters

    • host: string

      Hostname of target server.

    Returns boolean

    True if the specified server exists, and false otherwise.

    Remarks

    RAM cost: 0.1 GB

  • Set the title of the tail window of a script.

    Parameters

    • title: ReactNode

      The new title for the tail window.

    • Optional pid: number

      Optional. PID of the script having its tail closed. If omitted, the current script is used.

    Returns void

    Remarks

    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.

  • Share the server's ram with your factions.

    Returns Promise<void>

    Remarks

    RAM cost: 2.4 GB

    Increases rep/second for all faction work while share is running. Each cycle of ns.share() is 10 seconds. Scales with thread count, but at a sharply decreasing rate.

  • Suspends the script for n milliseconds.

    Parameters

    • millis: number

      Number of milliseconds to sleep.

    Returns Promise<true>

    A promise that resolves to true when the sleep is completed.

    Remarks

    RAM cost: 0 GB

    Example

    // 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.

    Parameters

    • script: string

      Filename of script to execute.

    • Optional threadOrOptions: number | SpawnOptions

      Either 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.

    Returns void

    Remarks

    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.

    Example

    //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);
  • Runs SQLInject.exe on a server.

    Parameters

    • host: string

      Hostname of the target server.

    Returns void

    Remarks

    RAM cost: 0.05 GB

    Runs the SQLInject.exe program on the target server. SQLInject.exe must exist on your home computer.

    Example

    ns.sqlinject("foodnstuff");
    
  • Format time to a readable string.

    Parameters

    • milliseconds: number

      Number of millisecond to format.

    • Optional milliPrecision: boolean

      Format time with subsecond precision. Defaults to false.

    Returns string

    The formatted time.

    Remarks

    RAM cost: 0 GB

  • Open the tail window of a script.

    Parameters

    • Optional fn: FilenameOrPID

      Optional. Filename or PID of the script being tailed. If omitted, the current script is tailed.

    • Optional host: string

      Optional. 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.

    Returns void

    Remarks

    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.

    Example

    //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).

    Parameters

    • msg: string

      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 | number

      Duration of toast in ms. Can also be null to create a persistent toast. Defaults to 2000.

    Returns void

  • Prints one or more values or variables to the Terminal.

    Parameters

    • Rest ...args: any[]

      Value(s) to be printed.

    Returns void

    Remarks

    RAM cost: 0 GB

    See print for how to add color to your printed strings.

  • Prints a raw value or a variable to the Terminal.

    Parameters

    • format: string

      Format of the message.

    • Rest ...values: any[]

      Value(s) to be printed.

    Returns void

    Remarks

    RAM cost: 0 GB

  • Attempt to write to a port.

    Parameters

    • portNumber: number

      Port to attempt to write to. Must be a positive integer.

    • data: any

      Data to write, it's cloned with structuredClone().

    Returns boolean

    True if the data is successfully written to the port, and false otherwise.

    Remarks

    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.

    Parameters

    • hostname: string

      Hostname of the server to upgrade.

    • ram: number

      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).

    Returns boolean

    True if the upgrade succeeded, and false otherwise.

    Remarks

    RAM cost: 0.25 GB

  • Reduce a server's security level.

    Parameters

    • host: string

      Hostname of the target server to weaken.

    • Optional opts: BasicHGWOptions

      Optional parameters for configuring function behavior.

    Returns Promise<number>

    A promise that resolves to the value by which security was reduced.

    Remarks

    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.

    Example

    let currentSecurity = ns.getServerSecurityLevel("foodnstuff");
    currentSecurity -= await ns.weaken("foodnstuff");
  • Predict the effect of weaken.

    Parameters

    • threads: number

      Amount of threads that will be used.

    • Optional cores: number

      Optional. The number of cores of the server that would run weaken.

    Returns number

    The security decrease.

    Remarks

    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.

    Parameters

    • url: string

      URL to pull data from.

    • target: string

      Filename to write data to. Must be script or text file.

    • Optional host: string

      Optional hostname/ip of server for target file.

    Returns Promise<boolean>

    True if the data was successfully retrieved from the URL, false otherwise.

    Remarks

    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.

    Example

    await ns.wget("https://raw.githubusercontent.com/bitburner-official/bitburner-src/master/README.md", "game_readme.txt");
    
  • Write data to a file.

    Parameters

    • filename: string

      Name of the file to be written to.

    • Optional data: string

      Data to write.

    • Optional mode: "w" | "a"

      Defines the write mode.

    Returns void

    Remarks

    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.

    Parameters

    • portNumber: number

      Port to write to. Must be a positive integer.

    • data: any

      Data to write, it's cloned with structuredClone().

    Returns any

    The data popped off the queue if it was full, or null if it was not full.

    Remarks

    RAM cost: 0 GB

    Write data to the given Netscript port.