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

时间:2017-07-16 05:58:05

标签: 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)

有人可以帮我这一点吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

您应该调用类似fs.createReadStream(path, {encoding: 'utf8'})的功能,参见docs

答案 1 :(得分:0)

使用管道解决问题:)

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

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

myReadStream.pipe(myWriteStream)