Javascript: how to make readline() work with node?

When I try to run my CG javascript or typescript puzzle solutions locally with node.js, it throws error, as readline() function is not defined.

How to make this work (preferably without having to modify the source code)? With some polyfills?

The node docs mention only a readline module with some async readline approach with different syntax, but not the simple readline() function my code needs.

I don’t think cg uses node native readline which is “asynchronous” (node 18) or at least requires a callback method to process the input data (making readline not usable in a “synchronous” way that’s to say ‘const input = readline(); doSomething(input)’)

In my opinion, if you want to keep readline in your local code, you will have to override it by some custom implementation.
const is local = false; // set to true in local only
If (isLocal) readline = customImplem;
// Insert rest of the code here

Thanks. I am noob in JavaScript, so not sure how to implement this. I though there is a polyfill library that can be referenced/imported, adding a sync readline(). Most likely the CG runtime does something similar when I submit my code there… It is just strange that the provided stub contains a function call that is not part of the core language…

This already had been discussed here btw.


It seems this meme also applies to JS and readline()…

I finally figured out that running this in the CG IDE (with selecting bash) reveals what polyfill is used by CG for the missing readline() function:

cat /codemachine/lib/javascript/internal/polyfill.js
cat /codemachine/lib/javascript/internal/readline.js

Saving these locally under a node_modules subdirectory, and adding -r polyfill.js when invoking node solves the problem.
PS: In Windows some more tweaking is needed, because the js code tries to open hard-coded /dev/stdin. Replacing this with a reference to process.stdin.fd seems to work both in Linux and Windows.

1 Like

Can you share the files? I can’t find it anywhere.

I am not keen on posting this file as I don’t know it’s copyright status.
But you can easily access it:

  • open a simple solo puzzle in the online IDE, for example this one
  • select bash as language
  • copy-paste this code into the ide:
read n
echo "// === copy-paste following lines to your local node_modules/polyfill.js file" >&2 
cat /codemachine/lib/javascript/internal/polyfill.js >&2 
echo "// === end of polyfill.js" >&2 
echo "// === copy-paste following lines to your local node_modules/readline.js file" >&2 
cat /codemachine/lib/javascript/internal/readline.js >&2
echo "// === end of readline.js" >&2 
echo "1"
  • play a testcase
  • copy-paste the result in the console output window to local files
  • invoke node with node yoursource.js -r polyfill.js