【问题标题】:Deno: how to take care of accents when reading from windows terminal prompt?Deno:从 Windows 终端提示符阅读时如何处理口音?
【发布时间】:2021-08-20 19:34:12
【问题描述】:

我正在尝试使用 Deno 读取用户输入,但我遇到了编码问题。

这是我输入“áé”时来自 Deno shell 的简单代码:

> const a = prompt('Insert your character:');
Insert your character: áé
undefined
> a
"��"

我的 Windows 命令提示符有 CP-1252 中的编码,与 ISO-8859-1 非常相似。

如何告诉 Deno 我输入的字符串的编码?或者我如何从 cp-1252 解码它?

【问题讨论】:

标签: unicode character-encoding deno


【解决方案1】:

这种行为可能会在未来的 Deno 版本中发生变化(请参阅 New prompt method gets confused when receiving special characters as input [ã] · Issue #8239 · denoland/deno),但现在如果您需要使用 prompt 使用的编码以外的编码(目前似乎总是 UTF-8)那么你可以直接使用实现Deno.ReaderDeno.stdin

例如使用readLines可以指定编码:

import { readLines } from "https://deno.land/std@0.105.0/io/bufio.ts";

async function prompt(
  message = "Prompt",
  { encoding }: { encoding?: string } = {}
) {
  await Deno.stdout.write(new TextEncoder().encode(`${message} `));
  const { value } = await readLines(Deno.stdin, { encoding }).next();
  return <string>value || null;
}

const a = await prompt("Insert your character:", { encoding: "windows-1252" });
console.log(a);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 2010-10-02
    • 1970-01-01
    相关资源
    最近更新 更多