The direct stream read in the channel, in the recorded stream

What's the difference between:

const stream = createReadStream(source).pipe(createWriteStream(destination));

stream.on("error", (error) => {
   stream.destroy();
   stream.removeListener("close");
   reject(error);
});
stream.on("close", () => {
  // do something
});

against

const writable = createWriteStream(destination);
const readable = createReadStream(source);
readable.on("error", onError);
writable.on("error", onError);
function onError(error) {
  readable.destroy();
  writable.destroy();
  writable.removeListener("close", onClose);
  reject(error);
}

And why should we manually destroy the thread if some kind of error occurs? Node will not do this automatically?

Thank.

+4
source share
1 answer

, -, . , "error" , , . "" . , Promise. , "", Promise . , "" , , , "" . , node , . , :

const fs = require('fs')

function copy (source, target) {
  return new Promise((resolve, reject) => {
    const rs = fs.createReadStream(source)
    const ws = fs.createWriteStream(target)
    rs.on('error', reject)
    ws.on('error', reject)
    rs.pipe(ws).on('close', resolve)
  })
}

:

copy('/foo/bar.json', '/baz/qux.json')
  .then(() => console.log('copy done'))
+6

Source: https://habr.com/ru/post/1673719/


All Articles