Standard library · Web and services

node

A Salam program under Node.js: modules, files, processes and JavaScript objects.

import node

This package is for Salam programs that are translated to JavaScript with salam build --platform=js and run under Node.js, such as the VS Code extension or a build script that has to live in an npm project. It gives you the whole of Node: Require loads any built-in or npm module, the Get... and Set... functions read and write properties, and the Call... functions call methods. A few helpers wrap the common fs, path, os and child_process calls.

Use it only when the program really runs under Node. A native Salam program reads files with fs and starts programs with os.process, and code for a browser page uses dom. A native build cannot call these functions, so the examples on this page are type-checked by the site but not run.

Core ideas

•

Handles. Every JavaScript value (object, array, function, promise, even undefined) is held in an i64. Nothing needs freeing; Node's garbage collector owns them.

•

Typed calls. Salam checks argument types, so each call shape has its own function, named after its arguments: CallS2 passes two strings, CallV1 one JavaScript value, CallSFn0 a string and a function. Pick the one that matches the method you call; the result is always a handle.

•

Callbacks run later. A Salam lambda passed to CallFn1, ExecFile or SetPropFn1 becomes a JavaScript function. Node calls it after main has returned, from its event loop.

Things that trip people up

•

GetStr on a missing property returns an empty string and GetNum returns 0, without any error. When "missing" and "empty" mean different things, test IsNullish(GetProp(obj, name)) first.

•

Every number from JavaScript is an f64, and 64-bit integers do not work under salam build --platform=js. Cast to int when you need one.

•

Salam strings count bytes, also under Node: "سلام".len() is 8, while JavaScript's length of the same text is 4. Text itself passes through unchanged.

To try a program, translate it and run the result with Node.js 18 or newer:

salam build node-guide-files.salam --platform=js --output=files.js
node files.js

The output under each program is what it printed that way under Node 24.

Files and directories

The file helpers wrap the synchronous calls of Node's fs and path modules, which keeps a script readable from top to bottom. For anything they do not cover, Require("fs") gives you the module itself. readdirSync returns a JavaScript array: its length is a number property and each element is a property named by its index, so GetStr(names, "0") reads the first one.

node-guide-files.salam
import node
import str

func main:
    folder := node.MkdtempSync(node.PathJoin2(node.TmpDir(), "salam-notes-"))
    node.WriteFileSync(node.PathJoin2(folder, "a.txt"), "one\ntwo\nthree\n")
    node.WriteFileSync(node.PathJoin2(folder, "b.txt"), "only line\n")
    node.WriteFileSync(node.PathJoin2(folder, "c.md"), "# title\n")
    fs := node.Require("fs")
    names := node.CallS1(fs, "readdirSync", folder)
    _ := node.Call0(names, "sort")
    mut total := 0
    repeat node.GetNum(names, "length") as int in i:
        name := node.GetStr(names, str.FromInt(i))
        if not str.EndsWith(name, ".txt"):
            continue
        end
        text := node.ReadFileSync(node.PathJoin2(folder, name))
        lines := str.Count(text, "\n")
        total += lines
        println name, lines
    end
    println "total", total
    node.RmSyncRecursiveForce(folder)
end
a.txt 3
b.txt 1
total 4

MkdtempSync adds random characters to the prefix, so two runs never collide; RmSyncRecursiveForce removes the directory and everything in it at the end.

Reading JSON from JavaScript

Global("JSON") is the same JSON object a JavaScript program sees, so parse turns text into an object handle and the Get... functions read its fields. A field that is missing comes back as undefined; test it with IsNullish before reading it, and fall back to a default.

node-guide-config.salam
import node

func main:
    text := `{"name": "shop", "port": 8080, "debug": true, "db": {"host": "127.0.0.1"}}`
    config := node.CallS1(node.Global("JSON"), "parse", text)
    println "name:", node.GetStr(config, "name")
    println "port:", node.GetNum(config, "port")
    println "debug:", node.GetBool(config, "debug")
    db := node.GetProp(config, "db")
    println "db host:", node.GetStr(db, "host")
    mut workers := 4.0
    if not node.IsNullish(node.GetProp(config, "workers")):
        workers = node.GetNum(config, "workers")
    end
    println "workers:", workers
    node.SetNum(config, "workers", workers)
    println node.ToStr(node.CallV1(node.Global("JSON"), "stringify", config))
end
name: shop
port: 8080
debug: true
db host: 127.0.0.1
workers: 4
{"name":"shop","port":8080,"debug":true,"db":{"host":"127.0.0.1"},"workers":4}

Numbers always arrive as f64, because JavaScript has only one number type. Cast with as int where you need an integer. Note the IsNullish test: GetNum(config, "workers") on its own would have returned 0 for the missing field, not an error.

Writing a Node module in Salam

Exports is module.exports of the translated file, so the functions you attach to it with SetPropFn0, SetPropFn1 and SetPropFn1R can be called by any JavaScript code that requires the file. Arguments and results are JavaScript values (i64 handles): ToStr turns one into a Salam string, and the small js_str helper here goes the other way by pushing the string into an array and reading it back.

node-guide-module.salam
import node
import str

func js_str(s: str): i64:
    box := node.NewArray()
    node.PushStr(box, s)
    ret node.GetProp(box, "0")
end

func slug(text: str): str:
    ret str.Replace(str.Lower(str.Trim(text)), " ", "-")
end

func main:
    exports := node.Exports()
    node.SetStr(exports, "name", "salam-slug")
    node.SetPropFn1R(exports, "slug", (x: i64): ret js_str(slug(node.ToStr(x))) end)
    node.SetPropFn0(exports, "hello", (): println "hello from Salam" end)
    _ := node.Call0(exports, "hello")
    println node.ToStr(node.Invoke1(node.GetProp(exports, "slug"), js_str("  Hello Salam World ")))
end
hello from Salam
hello-salam-world

From JavaScript the module is used as usual: require("./slug.js").slug("Some Title").

Child processes and events

ExecFile starts a program and returns at once; the function you pass runs later, when the program has finished, with a failure flag and everything it wrote to standard output and standard error. That is why started the child is printed first. An EventEmitter from the events module lets other parts of the program react when the work is done.

node-guide-exec.salam
import node
import str

func main:
    events := node.New0(node.GetProp(node.Require("events"), "EventEmitter"))
    _ := node.CallSFn0(events, "on", "finished", (): println "all jobs finished" end)
    args := node.NewArray()
    node.PushStr(args, "-e")
    node.PushStr(args, "console.log(6 * 7)")
    node.ExecFile("node", args, node.TmpDir(), (failed: bool, out: str, err: str): if failed: println "the child failed:", err ret end println "child printed", str.Trim(out) _ := node.CallS1(events, "emit", "finished") end)
    println "started the child"
end
started the child
child printed 42
all jobs finished

Node keeps the process alive while a child or a timer is pending, so main may return long before the callbacks run. Do not free or reuse anything a callback still needs.

failed is also true when the program ran but exited with a non-zero status. Both outputs are collected in memory, up to 32 MB each; a program that writes more is stopped and reported as failed. Use ExecFileRaw when you need the Node error object itself, for example its code property with the exit status.

Promises and asynchronous files

Most newer Node APIs return a promise instead of taking a callback. A promise is a handle like any other: call its then method with CallFn1 to run code with the result, catch to handle a failure and finally (with CallFn0) for cleanup that must run either way. Here fs.promises.readFile reads one file that exists and one that does not.

node-guide-promise.salam
import node
import str

func main:
    folder := node.MkdtempSync(node.PathJoin2(node.TmpDir(), "salam-orders-"))
    node.WriteFileSync(node.PathJoin2(folder, "orders.csv"), "id,total\n1,40\n2,25\n")
    fsp := node.GetProp(node.Require("fs"), "promises")
    orders := node.CallS2(fsp, "readFile", node.PathJoin2(folder, "orders.csv"), "utf8")
    _ := node.CallFn1(orders, "then", (text: i64): println "orders.csv has", str.Count(node.ToStr(text), "\n") - 1, "orders" refunds := node.CallS2(fsp, "readFile", node.PathJoin2(folder, "refunds.csv"), "utf8") caught := node.CallFn1(refunds, "catch", (err: i64): println "refunds.csv failed with", node.GetStr(err, "code") end) _ := node.CallFn0(caught, "finally", (): node.RmSyncRecursiveForce(folder) println "temp folder removed" end) end)
    println "reading started"
end
reading started
orders.csv has 2 orders
refunds.csv failed with ENOENT
temp folder removed

A Salam lambda cannot return a value to then, so promises do not chain the way they do in JavaScript. To run one step after another, start the next step inside the callback of the previous one, as the second read does here. NewPromise goes the other way and makes a promise of your own for JavaScript code to wait on: its function receives the resolve and reject functions, which you call with Invoke1.

Functions

Require

#
func Require(id: str): i64

Loads a Node module with require.

node-Basics.salam
import node

func main:
    println node.Platform().Len() > 0, node.IsWindows() == (node.Platform() == "win32")
    folder := node.MkdtempSync(node.PathJoin2(node.TmpDir(), "salam-"))
    path := node.PathJoin3(folder, "data", "note.txt")
    println node.PathDirname(path) == node.PathJoin2(folder, "data")
    fs := node.Require("fs")
    _ := node.CallS1(fs, "mkdirSync", node.PathDirname(path))
    node.WriteFileSync(path, "hello from node")
    println node.ReadFileSync(path)
    node.RmSyncRecursiveForce(folder)

    obj := node.NewObject()
    node.SetStr(obj, "name", "Maryam")
    node.SetNum(obj, "age", 30)
    node.SetBool(obj, "admin", true)
    arr := node.NewArray()
    node.PushStr(arr, "a")
    node.Push(arr, obj)
    node.SetProp(obj, "tags", arr)
    println node.GetStr(obj, "name"), node.GetNum(obj, "age"), node.GetBool(obj, "admin")
    println node.GetNum(node.GetProp(obj, "tags"), "length")
    json := node.Global("JSON")
    println node.ToStr(node.CallS1(json, "stringify", "x"))
    println node.IsNullish(node.GetProp(obj, "missing")), node.ToBool(node.GetProp(obj, "admin"))

    math := node.Global("Math")
    println node.ToStr(node.CallV2(math, "max", node.GetProp(obj, "age"), node.GetProp(obj, "age")))
    date := node.New1(node.Global("Date"), node.GetProp(obj, "age"))
    println node.ToStr(node.Call0(date, "getTime"))
    path_module := node.Require("path")
    println node.ToStr(node.CallS2(path_module, "join", "a", "b"))
    println node.ToStr(node.CallS3(path_module, "join", "a", "b", "c"))
    node.SetPropFn0(obj, "hello", (): println "hello from a function" end)
    _ := node.Call0(obj, "hello")
    node.SetPropFn1R(obj, "twice", (x: i64): ret node.CallV2(math, "max", x, x) end)
    println node.ToStr(node.Invoke1(node.GetProp(obj, "twice"), node.GetProp(obj, "age")))
    println node.IsNullish(node.Exports())
end

Exports

#
func Exports(): i64

The module.exports object; for building a module.

The example for this item is shown with the ones above: node-Basics.salam

GetProp

#
func GetProp(obj: i64, name: str): i64

A property of an object that is itself an object.

The example for this item is shown with the ones above: node-Basics.salam

GetNum

#
func GetNum(obj: i64, name: str): f64

A numeric property, as f64; 0 when it is missing.

The example for this item is shown with the ones above: node-Basics.salam

GetStr

#
func GetStr(obj: i64, name: str): str

A string property; an empty string when it is missing.

The example for this item is shown with the ones above: node-Basics.salam

GetBool

#
func GetBool(obj: i64, name: str): bool

A boolean property.

The example for this item is shown with the ones above: node-Basics.salam

SetProp

#
func SetProp(obj: i64, name: str, value: i64)

Sets a property on an object.

The example for this item is shown with the ones above: node-Basics.salam

SetStr

#
func SetStr(obj: i64, name: str, value: str)

A string property.

The example for this item is shown with the ones above: node-Basics.salam

SetNum

#
func SetNum(obj: i64, name: str, value: f64)

A numeric property.

The example for this item is shown with the ones above: node-Basics.salam

SetBool

#
func SetBool(obj: i64, name: str, value: bool)

A boolean property.

The example for this item is shown with the ones above: node-Basics.salam

SetPropFn0

#
func SetPropFn0(obj: i64, name: str, fn: func())

Makes a function of no arguments a property of the object, so JavaScript can call it.

The example for this item is shown with the ones above: node-Basics.salam

SetPropFn1

#
func SetPropFn1(obj: i64, name: str, fn: func(i64))

Makes a function of one argument a property.

node-Calls.salam
import node

func main:
    arr := node.New0(node.Global("Array"))
    node.PushStr(arr, "b")
    node.PushStr(arr, "a")
    _ := node.Call0(arr, "sort")
    println node.ToStr(node.CallS1(arr, "join", ", "))
    number := node.CallV1(
        node.Global("Math"), "abs", node.GetProp(node.Global("Number"), "MIN_SAFE_INTEGER")
    )
    println node.ToStr(number).Len() > 0
    println node.ToStr(
        node.CallV3(node.Global("Math"), "max", number, number, number)
    ) == node.ToStr(number)
    date := node.New4(
        node.Global("Date"), node.GetProp(node.Global("Number"), "EPSILON"), number, number, number
    )
    println node.IsNullish(date)
    buf := node.CallSB1(node.NewArray(), "includes", "x", false)
    println node.ToStr(buf)
    println node.ToStr(node.CallB1(node.Global("JSON"), "stringify", true))
    println node.ToStr(node.CallVS1(arr, "fill", node.GetProp(arr, "length"), "x"))

    emitter := node.New0(node.GetProp(node.Require("events"), "EventEmitter"))
    _ := node.CallSFn0(emitter, "on", "ping", (): println "the ping event arrived" end)
    _ := node.CallS1(emitter, "emit", "ping")
    node.SetPropFn1(emitter, "show", (x: i64): println "show:", node.ToStr(x) end)
    _ := node.Invoke2(node.GetProp(emitter, "show"), arr, arr)
    _ := node.Invoke0(node.GetProp(emitter, "show"))

    _ := node.CallFn0(node.Global("process"), "nextTick", (): println "after the current job" end)
    _ := node.CallFn1(arr, "forEach", (x: i64): println "element:", node.ToStr(x) end)
    promise := node.NewPromise((resolve: i64, reject: i64): _ := node.Invoke1(resolve, reject) end)
    println node.IsNullish(promise)

    args := node.NewArray()
    node.PushStr(args, "-e")
    node.PushStr(args, "console.log('hello from the child')")
    node.ExecFile("node", args, node.TmpDir(), (failed: bool, out: str, err: str): println "child:", failed, out.Len() > 0, err.Len() end)
    node.ExecFileRaw("node", args, node.TmpDir(), (code: i64, out: str, _err: str): println "raw child:", node.IsNullish(code), out.Len() > 0 end)
end

SetPropFn1R

#
func SetPropFn1R(obj: i64, name: str, fn: func(i64): i64)

Makes a function of one argument with a return value a property.

The example for this item is shown with the ones above: node-Basics.salam

Call0

#
func Call0(obj: i64, method: str): i64

Calls a method with no arguments.

The example for this item is shown with the ones above: node-Basics.salam

CallS1

#
func CallS1(obj: i64, method: str, a: str): i64

With one string.

The example for this item is shown with the ones above: node-Basics.salam

CallS2

#
func CallS2(obj: i64, method: str, a: str, b: str): i64

With two strings.

The example for this item is shown with the ones above: node-Basics.salam

CallS3

#
func CallS3(obj: i64, method: str, a: str, b: str, c: str): i64

With three strings.

The example for this item is shown with the ones above: node-Basics.salam

CallV1

#
func CallV1(obj: i64, method: str, a: i64): i64

With one JavaScript value.

The example for this item is shown with the ones above: node-Calls.salam

CallV2

#
func CallV2(obj: i64, method: str, a: i64, b: i64): i64

With two values.

The example for this item is shown with the ones above: node-Basics.salam

CallV3

#
func CallV3(obj: i64, method: str, a: i64, b: i64, c: i64): i64

With three values.

The example for this item is shown with the ones above: node-Calls.salam

CallVS1

#
func CallVS1(obj: i64, method: str, a: i64, b: str): i64

With one value and one string.

The example for this item is shown with the ones above: node-Calls.salam

CallSB1

#
func CallSB1(obj: i64, method: str, a: str, b: bool): i64

With one string and one boolean.

The example for this item is shown with the ones above: node-Calls.salam

CallB1

#
func CallB1(obj: i64, method: str, a: bool): i64

With one boolean.

The example for this item is shown with the ones above: node-Calls.salam

CallFn0

#
func CallFn0(obj: i64, method: str, fn: func()): i64

With a function of no arguments, as nextTick wants.

The example for this item is shown with the ones above: node-Calls.salam

CallFn1

#
func CallFn1(obj: i64, method: str, fn: func(i64)): i64

With a function of one argument, as forEach wants.

The example for this item is shown with the ones above: node-Calls.salam

CallSFn0

#
func CallSFn0(obj: i64, method: str, a: str, fn: func()): i64

With one string and a function, as on("event", ...) wants.

The example for this item is shown with the ones above: node-Calls.salam

New0

#
func New0(ctor: i64): i64

new with the given constructor.

The example for this item is shown with the ones above: node-Calls.salam

New1

#
func New1(ctor: i64, a: i64): i64

new with one argument.

The example for this item is shown with the ones above: node-Basics.salam

New4

#
func New4(ctor: i64, a: i64, b: i64, c: i64, d: i64): i64

new with four arguments.

The example for this item is shown with the ones above: node-Calls.salam

Invoke0

#
func Invoke0(fn: i64): i64

Calls a JavaScript function value.

The example for this item is shown with the ones above: node-Calls.salam

Invoke1

#
func Invoke1(fn: i64, a: i64): i64

With one argument.

The example for this item is shown with the ones above: node-Basics.salam

Invoke2

#
func Invoke2(fn: i64, a: i64, b: i64): i64

With two arguments.

The example for this item is shown with the ones above: node-Calls.salam

IsNullish

#
func IsNullish(x: i64): bool

The value is null or undefined.

The example for this item is shown with the ones above: node-Basics.salam

Global

#
func Global(name: str): i64

The global object with this name, such as JSON.

The example for this item is shown with the ones above: node-Basics.salam

NewArray

#
func NewArray(): i64

An empty array.

The example for this item is shown with the ones above: node-Basics.salam

NewObject

#
func NewObject(): i64

An empty object.

The example for this item is shown with the ones above: node-Basics.salam

Push

#
func Push(arr: i64, value: i64)

Adds a value to an array.

The example for this item is shown with the ones above: node-Basics.salam

PushStr

#
func PushStr(arr: i64, value: str)

Adds a string to an array.

The example for this item is shown with the ones above: node-Basics.salam

NewPromise

#
func NewPromise(executor: func(i64, i64)): i64

A new promise; the function takes the resolve and reject functions.

The example for this item is shown with the ones above: node-Calls.salam

ToStr

#
func ToStr(x: i64): str

Turns a value into a string with String.

The example for this item is shown with the ones above: node-Basics.salam

ToBool

#
func ToBool(x: i64): bool

Turns a value into a boolean.

The example for this item is shown with the ones above: node-Basics.salam

Platform

#
func Platform(): str

The operating system, such as linux or win32.

The example for this item is shown with the ones above: node-Basics.salam

IsWindows

#
func IsWindows(): bool

It is running on Windows.

The example for this item is shown with the ones above: node-Basics.salam

TmpDir

#
func TmpDir(): str

The system temporary directory.

The example for this item is shown with the ones above: node-Basics.salam

PathJoin2

#
func PathJoin2(a: str, b: str): str

Joins two path pieces.

The example for this item is shown with the ones above: node-Basics.salam

PathJoin3

#
func PathJoin3(a: str, b: str, c: str): str

Three pieces.

The example for this item is shown with the ones above: node-Basics.salam

PathDirname

#
func PathDirname(p: str): str

The directory of a path.

The example for this item is shown with the ones above: node-Basics.salam

MkdtempSync

#
func MkdtempSync(prefix: str): str

Makes a unique temporary directory with a prefix.

The example for this item is shown with the ones above: node-Basics.salam

WriteFileSync

#
func WriteFileSync(p: str, contents: str)

Writes a file.

The example for this item is shown with the ones above: node-Basics.salam

ReadFileSync

#
func ReadFileSync(p: str): str

Reads a file.

The example for this item is shown with the ones above: node-Basics.salam

RmSyncRecursiveForce

#
func RmSyncRecursiveForce(p: str)

Deletes a file or a directory with everything in it.

The example for this item is shown with the ones above: node-Basics.salam

ExecFile

#
func ExecFile(cmd: str, args: i64, cwd: str, cb: func(bool, str, str))

Runs a program with its arguments in the given directory and, once it finishes, calls the function with "it failed", the output and the error output. A non-zero exit status counts as a failure, and each output is capped at 32 MB.

The example for this item is shown with the ones above: node-Calls.salam

ExecFileRaw

#
func ExecFileRaw(cmd: str, args: i64, cwd: str, cb: func(i64, str, str))

The same, with the Node error object itself.

The example for this item is shown with the ones above: node-Calls.salam