읽을 수있는 스트림을 닫는 방법 (종료 전)?
Node.js에서 읽을 수있는 스트림 을 닫는 방법은 무엇입니까?
var input = fs.createReadStream('lines.txt');
input.on('data', function(data) {
// after closing the stream, this will not
// be called again
if (gotFirstLine) {
// close this stream and continue the
// instructions from this if
console.log("Closed.");
}
});
이것은 다음보다 낫습니다.
input.on('data', function(data) {
if (isEnded) { return; }
if (gotFirstLine) {
isEnded = true;
console.log("Closed.");
}
});
그러나 이것은 읽기 과정을 멈추지 않습니다 ...
호출 input.close()
. 문서에는 없지만
https://github.com/joyent/node/blob/cfcb1de130867197cbc9c6012b7e84e08e53d032/lib/fs.js#L1597-L1620
명확하게 작업을 수행합니다 isEnded
. :) 실제로 .
2015 년 4 월 19 일 수정 아래 의견을 바탕으로 명확히하고 업데이트합니다.
- 이 제안은 해킹이며 문서화되지 않았습니다.
- 현재를
lib/fs.js
살펴보면 1.5 년이 지난 후에도 여전히 작동합니다. destroy()
선호 하는 전화 에 대한 아래 의견에 동의합니다 .- 아래에서 올바르게 언급했듯이 이것은
fs
ReadStreams
일반이 아닌의Readable
일반적인 솔루션의 경우 : 적어도 문서에 대한 이해와을 간략히 살펴보면 하나가있는 것처럼 보이지 않습니다 _stream_readable.js
.
내 제안은 읽기 가능한 스트림을 일시 중지 모드로 설정하여 적어도 업스트림 데이터 소스에서 추가 처리를 방지합니다. 문서 에서 언급했듯이 실제로 일시 중지 되도록 unpipe()
모든 data
이벤트 리스너를 잊지 말고 제거하십시오.pause()
편집 : 좋은 소식입니다! Node.js 8.0.0부터 readable.destroy
공식적으로 사용할 수 있습니다 : https://nodejs.org/api/stream.html#stream_readable_destroy_error
ReadStream.destroy
언제든지 ReadStream.destroy 함수를 호출 할 수 있습니다 .
var fs = require('fs');
var readStream = fs.createReadStream('lines.txt');
readStream
.on('data', function (chunk) {
console.log(chunk);
readStream.destroy();
})
.on('end', function () {
// This may not been called since we are destroying the stream
// the first time 'data' event is received
console.log('All the data in the file has been read');
})
.on('close', function (err) {
console.log('Stream has been destroyed and file has been closed');
});
The public function ReadStream.destroy
is not documented (Node.js v0.12.2) but you can have a look at the source code on GitHub (Oct 5, 2012 commit).
The destroy
function internally mark the ReadStream
instance as destroyed and calls the close
function to release the file.
You can listen to the close event to know exactly when the file is closed. The end event will not fire unless the data is completely consumed.
Note that the destroy
(and the close
) functions are specific to fs.ReadStream. There are not part of the generic stream.readable "interface".
Today, in Node 10
readableStream.destroy()
is the official way to close a readable stream
see https://nodejs.org/api/stream.html#stream_readable_destroy_error
You can't. There is no documented way to close/shutdown/abort/destroy a generic Readable stream as of Node 5.3.0. This is a limitation of the Node stream architecture.
As other answers here have explained, there are undocumented hacks for specific implementations of Readable provided by Node, such as fs.ReadStream. These are not generic solutions for any Readable though.
If someone can prove me wrong here, please do. I would like to be able to do what I'm saying is impossible, and would be delighted to be corrected.
EDIT: Here was my workaround: implement .destroy()
for my pipeline though a complex series of unpipe()
calls. And after all that complexity, it doesn't work properly in all cases.
EDIT: Node v8.0.0 added a destroy()
api for Readable streams.
At version 4.*.*
pushing a null value into the stream will trigger a EOF
signal.
From the nodejs docs
If a value other than null is passed, The push() method adds a chunk of data into the queue for subsequent stream processors to consume. If null is passed, it signals the end of the stream (EOF), after which no more data can be written.
This worked for me after trying numerous other options on this page.
This destroy module is meant to ensure a stream gets destroyed, handling different APIs and Node.js bugs. Right now is one of the best choice.
NB. From Node 10 you can use the .destroy
method without further dependencies.
You can clear and close the stream with yourstream.resume()
, which will dump everything on the stream and eventually close it.
From the official docs:
readable.resume():
Return: this
This method will cause the readable stream to resume emitting 'data' events.
This method will switch the stream into flowing mode. If you do not want to consume the data from a stream, but you do want to get to its 'end' event, you can call stream.resume() to open the flow of data.
var readable = getReadableStreamSomehow();
readable.resume();
readable.on('end', () => {
console.log('got to the end, but did not read anything');
});
It's an old question but I too was looking for the answer and found the best one for my implementation. Both end
and close
events get emitted so I think this is the cleanest solution.
This will do the trick in node 4.4.* (stable version at the time of writing):
var input = fs.createReadStream('lines.txt');
input.on('data', function(data) {
if (gotFirstLine) {
this.end(); // Simple isn't it?
console.log("Closed.");
}
});
For a very detailed explanation see: http://www.bennadel.com/blog/2692-you-have-to-explicitly-end-streams-after-pipes-break-in-node-js.htm
This code here will do the trick nicely:
function closeReadStream(stream) {
if (!stream) return;
if (stream.close) stream.close();
else if (stream.destroy) stream.destroy();
}
writeStream.end() is the go-to way to close a writeStream...
참고URL : https://stackoverflow.com/questions/19277094/how-to-close-a-readable-stream-before-end
'your programing' 카테고리의 다른 글
숫자가 아닌 값을 포함하는 numpy.ndarray의 모든 행을 제거하는 방법 (0) | 2020.10.14 |
---|---|
.htpasswd에 사용자 추가 (0) | 2020.10.14 |
jscs가 파일, 블록 또는 줄당 규칙을 무시하는 방법이 있습니까? (0) | 2020.10.14 |
Python 2에서 부모 범위의 변수에 어떻게 쓰나요? (0) | 2020.10.14 |
Git에서 부모없이 커밋을 생성하려면 어떻게해야합니까? (0) | 2020.10.14 |