javascript - 在 Node.js 中使用 WriteStream 写入文件时出现编码错误

标签 javascript node.js

我只是读取一个文本文件并将其写回 Node.js 中的另一个文件。我还定义了编码类型('utf8),但它似乎不起作用:

    var http = require('http')
    var fs = require('fs')

    var myReadStream = fs.createReadStream(__dirname + '/readme.txt','utf8')
    var myWriteStream = fs.createWriteStream(__dirname, '/writtenText.txt','utf8')

    /* The event name is called data */
    myReadStream.on('data', function(chunk){
        myWriteStream.write(chunk)
    })

我面临的错误是:

    internal/fs.js:21
    throw new Error(`Unknown encoding: ${encoding}`);
    ^

Error: Unknown encoding: /writtenText.txt
    at assertEncoding (internal/fs.js:21:11)
    at getOptions (fs.js:80:5)
    at new WriteStream (fs.js:2057:24)
    at Object.fs.createWriteStream (fs.js:2048:10)
    at Object.<anonymous> (C:\Users\meThoz\Desktop\NodeFundamentals\Streams & Buffers\Writable Stream\App.js:5:24)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)

有人可以帮我解决这个问题吗?提前致谢。

最佳答案

您应该调用诸如fs.createReadStream(path, {encoding: 'utf8'})之类的函数,参见 docs

关于javascript - 在 Node.js 中使用 WriteStream 写入文件时出现编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45125532/

相关文章:

javascript - 项目是 unfiend 在 Kendo Grid 组中

javascript - Rack-Cors 并在 500 或 403 错误时发送 header

node.js - 在 nodejs 中生成参数中带有空格的 unix 命令

node.js - 打印最后的终端内容

javascript - 在 React 中将事件传播到子组件

javascript - 来自 Json 的 Google 图表 "undefined is not a function"

javascript - 在不显式转发所有函数的情况下装饰类实例

javascript - Node.js - 使用 NVM 配置 $NODE_PATH

javascript - 使用 filter() thisArg 编译 TypeScript

Node.js 类型错误 : connect ECONNREFUSED 127. 0.0.1:3000