@@ -145,7 +145,67 @@ function setupKillAndExit() {
145145 process . _exiting = true ;
146146 process . emit ( 'exit' , process . exitCode || 0 ) ;
147147 }
148+
149+ // Flush stdio streams prior to exit.
150+ // `flushSync` not present if stream redirected to file in shell.
151+ flushSync ( process . stdout ) ;
152+ flushSync ( process . stderr ) ;
153+
148154 process . reallyExit ( process . exitCode || 0 ) ;
155+
156+ function flushSync ( stream ) {
157+
158+ // FIXME: Behavior of this function outside of process.exit() is
159+ // undefined due to the following factors:
160+ // * Stream fd may be blocking after this call.
161+ // * In the event of an incomplete flush pending buffered write
162+ // requests may be truncated.
163+ // * No return code.
164+
165+ if ( stream . _writev )
166+ return ;
167+
168+ var handle = stream . _handle ;
169+ if ( ! handle || ! handle . flushSync )
170+ return ;
171+
172+ var fd = handle . fd ;
173+ if ( typeof fd !== 'number' || fd < 0 )
174+ return ;
175+
176+ // FIXME: late module resolution avoids cross require problem
177+ const fs = require ( 'fs' ) ;
178+
179+ // Queued libuv writes must be flushed first.
180+ // Note: fd will set to blocking after handle.flushSync()
181+ if ( handle . flushSync ( ) !== 0 ) {
182+ // bad fd or write queue for libuv stream not entirely flushed
183+ return ;
184+ }
185+
186+ // then the queued stream chunks can be flushed
187+ var state = stream . _writableState ;
188+ var entry = state . bufferedRequest ;
189+ while ( entry ) {
190+ var chunk = entry . chunk ;
191+ if ( ! ( chunk instanceof Buffer ) ) {
192+ chunk = Buffer . from ( chunk , entry . encoding ) ;
193+ }
194+ // Note: fd is blocking at this point
195+ var written = fs . writeSync ( fd , chunk , 0 , chunk . length ) ;
196+ if ( written !== chunk . length ) {
197+ // stream chunk not flushed entirely - stop writing.
198+ // FIXME: buffered request queue should be repaired here
199+ // rather than being truncated after loop break
200+ break ;
201+ }
202+ entry = entry . next ;
203+ }
204+
205+ state . bufferedRequestCount = 0 ;
206+ state . bufferedRequest = null ;
207+ state . lastBufferedRequest = null ;
208+ }
149209 } ;
150210
151211 process . kill = function ( pid , sig ) {
0 commit comments