js-new for npm package constructor

8 views
Skip to first unread message

Christoph Lange

unread,
Jun 30, 2017, 4:58:29 AM6/30/17
to BiwaScheme

I'm trying to implement this very simple first step from the TeleBot node package home page (https://www.npmjs.com/package/telebot):

const TeleBot = require('telebot');
const bot = new TeleBot('TELEGRAM_BOT_TOKEN');

I try:

(define (require npm)
   
(js-eval
     
(string-append "require('" npm "')")))

(define TeleBot (require "telebot"))
(define telegram-token "TELEGRAM_BOT_TOKEN")
(define bot (js-new "TeleBot" telegram-token))

But obviously I'm not getting a callable constructor 'TeleBot' this way, since biwas fails with 'ReferenceError: TeleBot is not defined [js-new]'. The 'js-new' example from the biwas homepage, however, works ('js-new "Date"'). My 'TeleBot' is of type function, while 'Date' is just unbound.

How do I properly get my TeleBot constructor?

Yutaka Hara

unread,
Jun 30, 2017, 1:59:19 PM6/30/17
to biwas...@googlegroups.com
Hello,

The first argument must be a JavaScript expression that evaluates to the constructor. So you 
need to define a variable "TeleBot" somehow in the JavaScript world, but it looks like
difficult in this case... 

Here's a workaround I found (ugly, but works.)

(define (require npm)
     (js-eval
            (string-append "BiwaScheme.TeleBot = require('" npm "')")))

(require "telebot")
(define telegram-token "TELEGRAM_BOT_TOKEN")
(define bot (js-new "BiwaScheme.TeleBot" telegram-token))


Ideally, 'js-new' should accept raw javascript function like:

  ...
 (define TeleBot (require "telebot"))
  (js-new TeleBot 'TELEGRAM_BOT_TOKEN')

I thought this is impossible when I first implemented 'js-new'. However, today I found a trick
to achieve this from https://babeljs.io/docs/plugins/transform-es2015-spread/ (It looks like:

  new (Function.prototype.bind.apply(Date, [null].concat([2014, 0, 1])))();

So I'll improve 'js-new' in the next release of BiwaScheme.

-- 
Yutaka HARA
Reply all
Reply to author
Forward
0 new messages