如何使用 Conduit 保存文件?

How do you save a file using Conduit?

如何使用 conduit 的库保存文件?我查看了 conduit 的教程,但似乎找不到任何东西,这是我的用例:

main :: IO ()
main = do
  xxs  <- lines <$> (readFile filePath)
  sourceList xxs =$ pipe $$ saveFile

pipe :: Monad m => Conduit String m String
pipe = undefined

所以这里有两个问题:

  1. 使用lines将字符串转换为列表有意义吗 字符串,然后将其提供给 sourceList?

  2. 我应该如何实现 saveFile 函数,以便当字符串 xxs 已完全处理,我可以将其写入磁盘吗?

您尝试使用 conduit 库执行的操作的一个小示例:

#!/usr/bin/env stack
{- stack
     --resolver lts-6.7
     --install-ghc
     runghc
     --package conduit-extra
     --package resourcet
     --package conduit
 -}

import Data.Conduit.Binary (sinkFile, sourceFile)
import Control.Monad.Trans.Resource
import Data.Conduit (($$), await, Conduit, (=$), yield)
import Data.Monoid ((<>))
import Control.Monad.IO.Class

myConduit = do
  str <- await
  case str of
    Just x -> do
              liftIO $ print "some processing"
              yield x
              myConduit
    Nothing -> return ()


saveFile :: FilePath -> FilePath -> IO ()
saveFile f1 f2 = runResourceT $ sourceFile f1 $$ myConduit =$ sinkFile f2

main :: IO ()                 
main = saveFile "test.txt" "atest.txt"

How should I implement the saveFile function so that when the strings xxs are fully processed, I can write it to disk?

您在 myConduit 函数中实现了它。请注意,在您的示例中,您使用的是 readFile 函数调用,它将延迟读取文件。 Conduit 为读写文件提供了它自己的抽象,你应该使用它。