From e0d8242693da7d6c1eb5f2ae75cb224e8bc7397b Mon Sep 17 00:00:00 2001
From: zhenweijin <zhenwei.jin@intel.com>
Date: Fri, 1 Dec 2023 19:35:05 +0800
Subject: [PATCH] stream: fix fd is null when calling clearBuffer

---
 lib/internal/streams/writable.js         |  3 ++-
 test/parallel/test-file-write-stream5.js | 28 ++++++++++++++++++++++++
 2 files changed, 30 insertions(+), 1 deletion(-)
 create mode 100644 test/parallel/test-file-write-stream5.js

diff --git a/lib/internal/streams/writable.js b/lib/internal/streams/writable.js
index e55ddc1796cf6c..0dbf56d7a69ca9 100644
--- a/lib/internal/streams/writable.js
+++ b/lib/internal/streams/writable.js
@@ -733,7 +733,8 @@ function errorBuffer(state) {
 
 // If there's something in the buffer waiting, then process it.
 function clearBuffer(stream, state) {
-  if ((state[kState] & (kDestroyed | kBufferProcessing | kCorked | kBuffered)) !== kBuffered) {
+  if ((state[kState] & (kDestroyed | kBufferProcessing | kCorked | kBuffered | kConstructed)) !==
+      (kBuffered | kConstructed)) {
     return;
   }
 
diff --git a/test/parallel/test-file-write-stream5.js b/test/parallel/test-file-write-stream5.js
new file mode 100644
index 00000000000000..cdc8b52eebd48d
--- /dev/null
+++ b/test/parallel/test-file-write-stream5.js
@@ -0,0 +1,28 @@
+'use strict';
+
+// Test 'uncork' for WritableStream.
+// Refs: https://github.com/nodejs/node/issues/50979
+
+const common = require('../common');
+const fs = require('fs');
+const assert = require('assert');
+const test = require('node:test');
+const tmpdir = require('../common/tmpdir');
+
+const filepath = tmpdir.resolve('write_stream.txt');
+tmpdir.refresh();
+
+const data = 'data';
+
+test('writable stream uncork', () => {
+  const fileWriteStream = fs.createWriteStream(filepath);
+
+  fileWriteStream.on('finish', common.mustCall(() => {
+    const writtenData = fs.readFileSync(filepath, 'utf8');
+    assert.strictEqual(writtenData, data);
+  }));
+  fileWriteStream.cork();
+  fileWriteStream.write(data, common.mustCall());
+  fileWriteStream.uncork();
+  fileWriteStream.end();
+});
