&| What | '''tcl-duktape''' |&
&| Where | https://github.com/dbohdan/tcl-duktape |&
&| Description | A binary Tcl [extension] that proves bindings for Duktape, an embedded [JavaScript] interpreter. |&
&| Online demo | https://rkeene.dev/js-repl/ hosts an integrated Tcl/JS REPL shell. |&
&| Platforms | Tested on Linux and FreeBSD. |&
&| Prerequisites | Tcl 8.5 or newer, [TclOO] required for the OO wrapper. |&&| Updated | 2019-207-160-23 (v0.79.0) |&
&| License | MIT |&&| Contact | [dbohdan] |&
Duktape is just a pair of .c/.h files, which makes the package easy to build. tcl-duktape allows you to call JavaScript code from Tcl and exposes a `jsproc` interface similar to the `cproc` interface in [Critcl] that allows you to write procedures in JavaScript. Included in the package is a TclOO API wrapper for tcl-duktape objects and one for [JSON] objects.
** Sample code **
======
#!/usr/bin/env tclsh
package require duktape
package require duktape::oo
set duktapeObj [::duktape::oo::Duktape new]
$duktapeObj jsproc ::add {{a 0 number} {b 0 number}} {
return a + b;
}
puts [add 1 2]
$duktapeObj jsmethod cos {{deg 0 number}} {
return Math.cos(deg * Math.PI / 180);
}
puts [$duktapeObj cos 360]
$duktapeObj destroy
======
** Discussion **
[wiwo] 17.02.2017: How can modules be loaded? When I try to load a JS file with require, I get "ReferenceError: identifier 'require' undefined"
[dbohdan] 2017-02-23: Duktape can't access the file system and thus has no [Node.js]-style `require()`. What you can do is read the module file in Tcl code and then have an interpreter instance `eval` it. There is an https://github.com/dbohdan/tcl-duktape/wiki/chess.js-example%|%example%|% that does this on the project wiki.
** Uses **
* [Chess4Tcl]
* [JSON value extraction benchmark]
** See also **
* [LuaJIT%|%LuaJIT bindings]
* [tcljs]
<<categories>>Foreign Interfaces | Package