Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling nim proc from NodeJs

Tags:

nim-lang

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?

like image 758
Nick Humrich Avatar asked Jul 03 '20 04:07

Nick Humrich


1 Answers

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

like image 128
hola Avatar answered Nov 04 '22 22:11

hola