Use Haskell to Output Utf8 String in the PowerShell on Windows 10

Viewed 117

Here is the code.

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
someFunc = putStrLn "你好"

I tried to run the program in the PowerShell on Windows 10.

chcp 936
stack run

And the output is:

─π║├

Here is another try:

chcp 65001
stack run

And the output is:

你好

Any suggestion to make it work appropriately?

1 Answers

chcp doesn't work from inside PowerShell, due to caching performed by .NET.

You can perform an equivalent command in PowerShell as follows, using the equivalent of
chcp 65001 (changing to the UTF-8 code page) as an example:

[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = 
  [System.Text.Utf8Encoding]::new()  # BOM-less UTF-8

To get other encodings, by their Windows code-page number (or name), use [System.Text.Encoding]::GetEncoding().

See this answer for background information.

Related