简体   繁体   中英

node.js fs.createReadStream error when use .pipe()

Using this function, I am trying to have the input be rendered to a file

function Write(err, content, output) {
    if (err) { console.error(err) };
    var fs = require('fs');
    var inp = fs.createReadStream(content);
    var out = fs.createWriteStream(output);
    inp.pipe(out);
}

for example...

write('some text', 'write-test.txt');

however running the above as a test i get the following returned

2) The Write module should write to test.txt:
     TypeError: path must be a string
      at Object.fs.open (fs.js:418:11)
      at open (/Users/joshburns/Code/micro-format/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/graceful-fs.js:60:16)
      at Object.gracefulOpen [as open] (/Users/joshburns/Code/micro-format/node_modules/grunt/node_modules/rimraf/node_modules/graceful-fs/graceful-fs.js:45:3)
      at WriteStream.open (fs.js:1654:6)
      at new WriteStream (fs.js:1644:10)
      at Object.fs.createWriteStream (fs.js:1608:10)
      at Write (/Users/joshburns/Code/micro-format/lib/write.js:9:450)
      at Context.<anonymous> (/Users/joshburns/Code/micro-format/test/write/index.js:8:4)
      at Test.Runnable.run (/Users/joshburns/Code/micro-format/node_modules/grunt-mocha-test/node_modules/mocha/lib/runnable.js:211:32)
      at Runner.runTest (/Users/joshburns/Code/micro-format/node_modules/grunt-mocha-test/node_modules/mocha/lib/runner.js:358:10)

The first parameter in your example is err and not content , and output is undefined and this is the cause of the error message.

Also: Read the documentation: fs.createReadStream expects a filename, not the contents. What you probably want is either fs.writeFile or fs.open combined with fs.write .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM