From 688bf397f2089d74a2e238b829dadf9416da6545 Mon Sep 17 00:00:00 2001 From: Andrii Kurdiumov Date: Fri, 17 Mar 2023 17:21:41 +0600 Subject: [PATCH] Add support for reading non-ASCII characters on Windows That's probably half-backed measurement, but at least it allow end-application alleviate issue. For example to read Cyrillic you need to ```bash chcp 1251 ``` and pass `windows-1251` to `encoding` property of config object. --- README.md | 2 ++ index.js | 10 +++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 2e72e71..ce1d4e6 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,8 @@ Takes `config` option with the following possible properties `history`: Takes an object that supplies a "history interface", see [prompt-sync-history](http://npm.im/prompt-sync-history) for an example. +`encoding`: Default is `utf-8`. On Windows used for decoding of non-ASCII characters. For Cyrillic specify `windows-1251` for example. + ## `prompt(ask, value, opts)` `ask` is the label of the prompt, `value` is the default value diff --git a/index.js b/index.js index 076d9f8..ea2846d 100644 --- a/index.js +++ b/index.js @@ -21,6 +21,8 @@ function create(config) { config = config || {}; var sigint = config.sigint; var eot = config.eot; + var encoding = config.encoding || 'utf-8'; + const decoder = new TextDecoder(encoding); var autocomplete = config.autocomplete = config.autocomplete || function(){return []}; var history = config.history; @@ -140,7 +142,9 @@ function create(config) { // if it is not a control character seq, assume only one character is read character = buf[read-1]; - + const codePoint = process.platform == 'win32' + ? decoder.decode(buf.subarray(0, read)) + : String.fromCharCode(character); // catch a ^C and return null if (character == 3){ process.stdout.write('^C\n'); @@ -200,9 +204,9 @@ function create(config) { insert--; process.stdout.write('\u001b[2D'); } else { - if ((character < 32 ) || (character > 126)) + if (character < 32) continue; - str = str.slice(0, insert) + String.fromCharCode(character) + str.slice(insert); + str = str.slice(0, insert) + codePoint + str.slice(insert); insert++; };