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