calling nim proc from NodeJs
Asked Answered
M

1

8

Following the docs here: https://nim-lang.org/docs/backends.html#backends-the-javascript-target

I have the following code in fib.nim

proc fib(a: cint): cint {.exportc.} =
  if a <= 2:
    result = 1
  else:
    result = fib(a - 1) + fib(a - 2)

If I run nim js -o:fib.js fib.nim then it compiles it to JS.

How do I then run fib from nodejs? In the example, its an html file and a browser, but on node, I cant figure out how to import the fib function. It looks like the .js file is missing the exports. How can I build the nim module so that nodejs can import it?

Meritorious answered 3/7, 2020 at 4:40 Comment(1)
I think that you need an extra layer to convert the plain javascript file created by the nim compiler into a javascript file which meets nodejs's expected syntax. I'm a little surprised that isn't an existing compiler option in nim.Harod
S
7

I can't find a built in way of compiling a nim module to a js module. The workaround is to import the module object and export procs.

import jsffi

var module {.importc.}: JsObject

proc fib*(a: cint): cint =
  if a <= 2:
    result = 1
  else:
    result = fib(a - 1) + fib(a - 2)

module.exports.fib = fib

The above can be expressed as a macro:

import macros, jsfii

var module {.importc.}: JsObject

macro exportjs(body: typed) =
  let bodyName = body.name.strVal
  result = newStmtList(
    body,
    newAssignment(
      newDotExpr(newDotExpr(ident"module", ident"exports"), ident(bodyName)),
      ident(bodyName)
    )
  )

proc fib*(a: cint): cint {.exportjs.} =
  if a <= 2:
    result = 1
  else:
    result = fib(a - 1) + fib(a - 2)

This repo came up while looking up solutions: https://github.com/nepeckman/jsExport.nim

Sommelier answered 4/7, 2020 at 11:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.