0

I'm simply reading a text file and writing that back to another file in Node.js. I have also defined the encoding type('utf8) but it doesn't seem to work:

    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)
    })

and the error i'm facing is:

    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)

Could someone help me with this a little bit? Thanks in advance.

2 Answers 2

1

You should call the functions like fs.createReadStream(path, {encoding: 'utf8'}), cf the docs

Sign up to request clarification or add additional context in comments.

Comments

0

Solved the problem by using Pipes :)

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)

1 Comment

The actual issue was that you used a comma instead of a + in the creation of myWriteStream.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.