Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/fs.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -79,6 +79,7 @@ const {
const {
FSReqCallback,
ReadFileJob,
WriteFileJob,
} = binding;
const { toPathIfFileURL } = require('internal/url');
const {
Expand DownExpand Up@@ -2929,6 +2930,23 @@ function writeFile(path, data, options, callback) {
if (checkAborted(options.signal, callback))
return;

if (!flush) {
// Open + write + close in one thread pool round trip.
const signal = options.signal;
path = getValidatedPath(path);
const job = new WriteFileJob(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
job.ondone = signal == null ? callback : (err) => {
// An abort that arrived while the write was in flight still wins.
callback(signal.aborted && !err ? new AbortError(undefined, { cause: signal.reason }) : err);
};
const accessError = job.run(path);
if (accessError !== undefined) {
callback(accessError);
}
return;
}

fs.open(path, flag, options.mode, (openErr, fd) => {
if (openErr) {
callback(openErr);
Expand Down
35 changes: 35 additions & 0 deletions lib/internal/fs/promises.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2116,6 +2116,14 @@ async function writeFile(path, data, options) {

checkAborted(options.signal);

if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) {
path = getValidatedPath(path);
await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
checkAborted(options.signal); // An abort during the write still wins.
return;
}

const fd = await open(path, flag, options.mode);
let writeOp = writeFileHandle(fd, data, options.signal, options.encoding);

Expand All@@ -2126,6 +2134,33 @@ async function writeFile(path, data, options) {
return handleFdClose(writeOp, fd.close);
}

/**
* Open + write + close as one thread pool round trip.
* @param {string|Buffer} path Validated path
* @param {number} flagsNumber
* @param {number} mode
* @param {ArrayBufferView} data
* @returns {Promise<void>}
*/
function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
return new Promise((resolve, reject) => {
const job = new binding.WriteFileJob(path, flagsNumber, mode, data);
job.ondone = (err) => {
if (err != null) {
ErrorCaptureStackTrace(err, writeFileInOneRoundTrip);
reject(err);
} else {
resolve();
}
};
const accessError = job.run(path);
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip);
reject(accessError);
}
});
}

function isCustomIterable(obj) {
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}
Expand Down
167 changes: 167 additions & 0 deletions src/node_file.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,6 +65,7 @@ namespace fs {

using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BigInt;
using v8::Context;
using v8::EscapableHandleScope;
Expand DownExpand Up@@ -3703,6 +3704,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
SET_SELF_SIZE(ReadFileJob)

private:
friend class WriteFileJob;
static constexpr size_t kUnknownSizeChunk = 64 * 1024;
static constexpr size_t kMaxReadChunk = 256 * 1024 * 1024;

Expand DownExpand Up@@ -3786,6 +3788,162 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
int fd_ = -1;
};

// Writes a whole buffer to a file in ONE thread pool round trip -- open +
// write (until everything is written) + close -- for fs.writeFile() and
// fs.promises.writeFile() with a path, which otherwise pay one round trip per
// step.
//
// JS: const job = new WriteFileJob(path, flags, mode, buffer);
// job.ondone = (err) => {...}; job.run(path);
// `err` carries the syscall that failed ('open', 'write' or 'close'); the file
// descriptor opened here is always closed.
class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
public:
static void New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
Environment* env = Environment::GetCurrent(args);
CHECK_GE(args.Length(), 4);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
CHECK(args[1]->IsInt32());
CHECK(args[2]->IsInt32());
CHECK(args[3]->IsArrayBufferView());
new WriteFileJob(env,
args.This(),
path.ToString(),
args[1].As<Int32>()->Value(),
args[2].As<Int32>()->Value(),
args[3].As<ArrayBufferView>());
}

// Returns undefined when the job was scheduled, or the ERR_ACCESS_DENIED
// error the asynchronous open() would have delivered (nothing is scheduled).
static void Run(const FunctionCallbackInfo<Value>& args) {
WriteFileJob* job;
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
Local<Value> access_error;
if (ReadFileJob::OpenPermissionError(env, path, job->flags_)
.ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
}
job->scheduled_ = true;
job->ClearWeak();
FS_ASYNC_TRACE_BEGIN0(UV_FS_WRITE, job)
job->ScheduleWork();
}

void DoThreadPoolWork() override {
uv_fs_t req;
int fd = uv_fs_open(nullptr, &req, path_.c_str(), flags_, mode_, nullptr);
uv_fs_req_cleanup(&req);
if (fd < 0) return Fail("open", fd);

size_t written = 0;
while (written < length_) {
uv_buf_t buf = uv_buf_init(data_ + written,
static_cast<unsigned int>(std::min<size_t>(
length_ - written, kMaxWriteChunk)));
int r = uv_fs_write(nullptr, &req, fd, &buf, 1, -1, nullptr);
uv_fs_req_cleanup(&req);
if (r < 0) {
Fail("write", r);
break;
}
written += static_cast<size_t>(r);
}

int rc = uv_fs_close(nullptr, &req, fd, nullptr);
uv_fs_req_cleanup(&req);
if (rc < 0 && error_ == 0) Fail("close", rc);
}

void AfterThreadPoolWork(int status) override {
Environment* env = AsyncWrap::env();
std::unique_ptr<WriteFileJob> self(this);
CHECK(status == 0 || status == UV_ECANCELED);
FS_ASYNC_TRACE_END0(UV_FS_WRITE, this)
if (status == UV_ECANCELED || !env->can_call_into_js()) return;
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Isolate* isolate = env->isolate();
Local<Value> argv[1] = {Null(isolate)};
if (error_ != 0) {
argv[0] = UVException(isolate,
error_,
syscall_,
nullptr,
syscall_ == kOpen ? path_.c_str() : nullptr);
}
MakeCallback(env->ondone_string(), arraysize(argv), argv);
}

bool IsNotIndicativeOfMemoryLeakAtExit() const override { return true; }
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("buffer", buffer_);
if (copy_) tracker->TrackFieldWithSize("copy", length_);
}
SET_MEMORY_INFO_NAME(WriteFileJob)
SET_SELF_SIZE(WriteFileJob)

private:
static constexpr size_t kMaxWriteChunk = 256 * 1024 * 1024;
static constexpr const char* kOpen = "open";

WriteFileJob(Environment* env,
Local<Object> object,
std::string&& path,
int flags,
int mode,
Local<ArrayBufferView> view)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
ThreadPoolWork(env, "fs.writefile"),
path_(std::move(path)),
flags_(flags),
mode_(mode) {
// Holding the backing store keeps the memory valid even if the buffer is
// detached or collected meanwhile; a resizable buffer can still have its
// pages decommitted by a shrink, so its contents are copied instead.
length_ = view->ByteLength();
backing_store_ = view->Buffer()->GetBackingStore();
if (backing_store_->IsResizableByUserJavaScript()) {
copy_.reset(new char[length_]);
memcpy(copy_.get(),
static_cast<char*>(backing_store_->Data()) + view->ByteOffset(),
length_);
data_ = copy_.get();
backing_store_.reset();
} else {
buffer_.Reset(env->isolate(), view);
data_ = static_cast<char*>(backing_store_->Data()) + view->ByteOffset();
}
MakeWeak();
}

void Fail(const char* syscall, int error) {
syscall_ = syscall;
error_ = error;
}

const std::string path_;
v8::Global<v8::ArrayBufferView> buffer_;
std::shared_ptr<v8::BackingStore> backing_store_;
std::unique_ptr<char[]> copy_;
char* data_ = nullptr;
size_t length_ = 0;
const int flags_;
const int mode_;
bool scheduled_ = false;
int error_ = 0;
const char* syscall_ = nullptr;
};

// Wrapper for readv(2).
//
// bytesRead = fs.readv(fd, buffers[, position], callback)
Expand DownExpand Up@@ -5103,6 +5261,13 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
SetProtoMethod(isolate, rfj, "run", ReadFileJob::Run);
SetConstructorFunction(isolate, target, "ReadFileJob", rfj);

Local<FunctionTemplate> wfj = NewFunctionTemplate(isolate, WriteFileJob::New);
wfj->InstanceTemplate()->SetInternalFieldCount(
WriteFileJob::kInternalFieldCount);
wfj->Inherit(AsyncWrap::GetConstructorTemplate(isolate_data));
SetProtoMethod(isolate, wfj, "run", WriteFileJob::Run);
SetConstructorFunction(isolate, target, "WriteFileJob", wfj);

// Create FunctionTemplate for FSReqCallback
Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback);
fst->InstanceTemplate()->SetInternalFieldCount(
Expand DownExpand Up@@ -5177,6 +5342,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Open);
registry->Register(ReadFileJob::New);
registry->Register(ReadFileJob::Run);
registry->Register(WriteFileJob::New);
registry->Register(WriteFileJob::Run);
registry->Register(OpenFileHandle);
registry->Register(Read);
registry->Register(ReadFileUtf8);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,7 +67,9 @@ async function checkAggregateError(op) {
tmpdir.refresh();
await checkAggregateError((filePath) => truncate(filePath));
await checkAggregateError((filePath) => readFile(filePath));
await checkAggregateError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkAggregateError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkAggregateError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-close-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -62,7 +62,9 @@ async function checkCloseError(op) {
tmpdir.refresh();
await checkCloseError((filePath) => truncate(filePath));
await checkCloseError((filePath) => readFile(filePath));
await checkCloseError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkCloseError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkCloseError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-op-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,7 +56,9 @@ async function checkOperationError(op) {
tmpdir.refresh();
await checkOperationError((filePath) => truncate(filePath));
await checkOperationError((filePath) => readFile(filePath));
await checkOperationError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkOperationError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkOperationError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/fs.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -79,6 +79,7 @@ const {
const {
FSReqCallback,
ReadFileJob,
WriteFileJob,
} = binding;
const { toPathIfFileURL } = require('internal/url');
const {
Expand DownExpand Up@@ -2929,6 +2930,23 @@ function writeFile(path, data, options, callback) {
if (checkAborted(options.signal, callback))
return;

if (!flush) {
// Open + write + close in one thread pool round trip.
const signal = options.signal;
path = getValidatedPath(path);
const job = new WriteFileJob(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
job.ondone = signal == null ? callback : (err) => {
// An abort that arrived while the write was in flight still wins.
callback(signal.aborted && !err ? new AbortError(undefined, { cause: signal.reason }) : err);
};
const accessError = job.run(path);
if (accessError !== undefined) {
callback(accessError);
}
return;
}

fs.open(path, flag, options.mode, (openErr, fd) => {
if (openErr) {
callback(openErr);
Expand Down
35 changes: 35 additions & 0 deletions lib/internal/fs/promises.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2116,6 +2116,14 @@ async function writeFile(path, data, options) {

checkAborted(options.signal);

if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) {
path = getValidatedPath(path);
await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
checkAborted(options.signal); // An abort during the write still wins.
return;
}

const fd = await open(path, flag, options.mode);
let writeOp = writeFileHandle(fd, data, options.signal, options.encoding);

Expand All@@ -2126,6 +2134,33 @@ async function writeFile(path, data, options) {
return handleFdClose(writeOp, fd.close);
}

/**
* Open + write + close as one thread pool round trip.
* @param {string|Buffer} path Validated path
* @param {number} flagsNumber
* @param {number} mode
* @param {ArrayBufferView} data
* @returns {Promise<void>}
*/
function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
return new Promise((resolve, reject) => {
const job = new binding.WriteFileJob(path, flagsNumber, mode, data);
job.ondone = (err) => {
if (err != null) {
ErrorCaptureStackTrace(err, writeFileInOneRoundTrip);
reject(err);
} else {
resolve();
}
};
const accessError = job.run(path);
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip);
reject(accessError);
}
});
}

function isCustomIterable(obj) {
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}
Expand Down
167 changes: 167 additions & 0 deletions src/node_file.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,6 +65,7 @@ namespace fs {

using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BigInt;
using v8::Context;
using v8::EscapableHandleScope;
Expand DownExpand Up@@ -3703,6 +3704,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
SET_SELF_SIZE(ReadFileJob)

private:
friend class WriteFileJob;
static constexpr size_t kUnknownSizeChunk = 64 * 1024;
static constexpr size_t kMaxReadChunk = 256 * 1024 * 1024;

Expand DownExpand Up@@ -3786,6 +3788,162 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
int fd_ = -1;
};

// Writes a whole buffer to a file in ONE thread pool round trip -- open +
// write (until everything is written) + close -- for fs.writeFile() and
// fs.promises.writeFile() with a path, which otherwise pay one round trip per
// step.
//
// JS: const job = new WriteFileJob(path, flags, mode, buffer);
// job.ondone = (err) => {...}; job.run(path);
// `err` carries the syscall that failed ('open', 'write' or 'close'); the file
// descriptor opened here is always closed.
class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
public:
static void New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
Environment* env = Environment::GetCurrent(args);
CHECK_GE(args.Length(), 4);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
CHECK(args[1]->IsInt32());
CHECK(args[2]->IsInt32());
CHECK(args[3]->IsArrayBufferView());
new WriteFileJob(env,
args.This(),
path.ToString(),
args[1].As<Int32>()->Value(),
args[2].As<Int32>()->Value(),
args[3].As<ArrayBufferView>());
}

// Returns undefined when the job was scheduled, or the ERR_ACCESS_DENIED
// error the asynchronous open() would have delivered (nothing is scheduled).
static void Run(const FunctionCallbackInfo<Value>& args) {
WriteFileJob* job;
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
Local<Value> access_error;
if (ReadFileJob::OpenPermissionError(env, path, job->flags_)
.ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
}
job->scheduled_ = true;
job->ClearWeak();
FS_ASYNC_TRACE_BEGIN0(UV_FS_WRITE, job)
job->ScheduleWork();
}

void DoThreadPoolWork() override {
uv_fs_t req;
int fd = uv_fs_open(nullptr, &req, path_.c_str(), flags_, mode_, nullptr);
uv_fs_req_cleanup(&req);
if (fd < 0) return Fail("open", fd);

size_t written = 0;
while (written < length_) {
uv_buf_t buf = uv_buf_init(data_ + written,
static_cast<unsigned int>(std::min<size_t>(
length_ - written, kMaxWriteChunk)));
int r = uv_fs_write(nullptr, &req, fd, &buf, 1, -1, nullptr);
uv_fs_req_cleanup(&req);
if (r < 0) {
Fail("write", r);
break;
}
written += static_cast<size_t>(r);
}

int rc = uv_fs_close(nullptr, &req, fd, nullptr);
uv_fs_req_cleanup(&req);
if (rc < 0 && error_ == 0) Fail("close", rc);
}

void AfterThreadPoolWork(int status) override {
Environment* env = AsyncWrap::env();
std::unique_ptr<WriteFileJob> self(this);
CHECK(status == 0 || status == UV_ECANCELED);
FS_ASYNC_TRACE_END0(UV_FS_WRITE, this)
if (status == UV_ECANCELED || !env->can_call_into_js()) return;
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Isolate* isolate = env->isolate();
Local<Value> argv[1] = {Null(isolate)};
if (error_ != 0) {
argv[0] = UVException(isolate,
error_,
syscall_,
nullptr,
syscall_ == kOpen ? path_.c_str() : nullptr);
}
MakeCallback(env->ondone_string(), arraysize(argv), argv);
}

bool IsNotIndicativeOfMemoryLeakAtExit() const override { return true; }
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("buffer", buffer_);
if (copy_) tracker->TrackFieldWithSize("copy", length_);
}
SET_MEMORY_INFO_NAME(WriteFileJob)
SET_SELF_SIZE(WriteFileJob)

private:
static constexpr size_t kMaxWriteChunk = 256 * 1024 * 1024;
static constexpr const char* kOpen = "open";

WriteFileJob(Environment* env,
Local<Object> object,
std::string&& path,
int flags,
int mode,
Local<ArrayBufferView> view)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
ThreadPoolWork(env, "fs.writefile"),
path_(std::move(path)),
flags_(flags),
mode_(mode) {
// Holding the backing store keeps the memory valid even if the buffer is
// detached or collected meanwhile; a resizable buffer can still have its
// pages decommitted by a shrink, so its contents are copied instead.
length_ = view->ByteLength();
backing_store_ = view->Buffer()->GetBackingStore();
if (backing_store_->IsResizableByUserJavaScript()) {
copy_.reset(new char[length_]);
memcpy(copy_.get(),
static_cast<char*>(backing_store_->Data()) + view->ByteOffset(),
length_);
data_ = copy_.get();
backing_store_.reset();
} else {
buffer_.Reset(env->isolate(), view);
data_ = static_cast<char*>(backing_store_->Data()) + view->ByteOffset();
}
MakeWeak();
}

void Fail(const char* syscall, int error) {
syscall_ = syscall;
error_ = error;
}

const std::string path_;
v8::Global<v8::ArrayBufferView> buffer_;
std::shared_ptr<v8::BackingStore> backing_store_;
std::unique_ptr<char[]> copy_;
char* data_ = nullptr;
size_t length_ = 0;
const int flags_;
const int mode_;
bool scheduled_ = false;
int error_ = 0;
const char* syscall_ = nullptr;
};

// Wrapper for readv(2).
//
// bytesRead = fs.readv(fd, buffers[, position], callback)
Expand DownExpand Up@@ -5103,6 +5261,13 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
SetProtoMethod(isolate, rfj, "run", ReadFileJob::Run);
SetConstructorFunction(isolate, target, "ReadFileJob", rfj);

Local<FunctionTemplate> wfj = NewFunctionTemplate(isolate, WriteFileJob::New);
wfj->InstanceTemplate()->SetInternalFieldCount(
WriteFileJob::kInternalFieldCount);
wfj->Inherit(AsyncWrap::GetConstructorTemplate(isolate_data));
SetProtoMethod(isolate, wfj, "run", WriteFileJob::Run);
SetConstructorFunction(isolate, target, "WriteFileJob", wfj);

// Create FunctionTemplate for FSReqCallback
Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback);
fst->InstanceTemplate()->SetInternalFieldCount(
Expand DownExpand Up@@ -5177,6 +5342,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Open);
registry->Register(ReadFileJob::New);
registry->Register(ReadFileJob::Run);
registry->Register(WriteFileJob::New);
registry->Register(WriteFileJob::Run);
registry->Register(OpenFileHandle);
registry->Register(Read);
registry->Register(ReadFileUtf8);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,7 +67,9 @@ async function checkAggregateError(op) {
tmpdir.refresh();
await checkAggregateError((filePath) => truncate(filePath));
await checkAggregateError((filePath) => readFile(filePath));
await checkAggregateError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkAggregateError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkAggregateError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-close-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -62,7 +62,9 @@ async function checkCloseError(op) {
tmpdir.refresh();
await checkCloseError((filePath) => truncate(filePath));
await checkCloseError((filePath) => readFile(filePath));
await checkCloseError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkCloseError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkCloseError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-op-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,7 +56,9 @@ async function checkOperationError(op) {
tmpdir.refresh();
await checkOperationError((filePath) => truncate(filePath));
await checkOperationError((filePath) => readFile(filePath));
await checkOperationError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkOperationError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkOperationError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/fs.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -79,6 +79,7 @@ const {
const {
FSReqCallback,
ReadFileJob,
WriteFileJob,
} = binding;
const { toPathIfFileURL } = require('internal/url');
const {
Expand DownExpand Up@@ -2929,6 +2930,23 @@ function writeFile(path, data, options, callback) {
if (checkAborted(options.signal, callback))
return;

if (!flush) {
// Open + write + close in one thread pool round trip.
const signal = options.signal;
path = getValidatedPath(path);
const job = new WriteFileJob(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
job.ondone = signal == null ? callback : (err) => {
// An abort that arrived while the write was in flight still wins.
callback(signal.aborted && !err ? new AbortError(undefined, { cause: signal.reason }) : err);
};
const accessError = job.run(path);
if (accessError !== undefined) {
callback(accessError);
}
return;
}

fs.open(path, flag, options.mode, (openErr, fd) => {
if (openErr) {
callback(openErr);
Expand Down
35 changes: 35 additions & 0 deletions lib/internal/fs/promises.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2116,6 +2116,14 @@ async function writeFile(path, data, options) {

checkAborted(options.signal);

if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) {
path = getValidatedPath(path);
await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
checkAborted(options.signal); // An abort during the write still wins.
return;
}

const fd = await open(path, flag, options.mode);
let writeOp = writeFileHandle(fd, data, options.signal, options.encoding);

Expand All@@ -2126,6 +2134,33 @@ async function writeFile(path, data, options) {
return handleFdClose(writeOp, fd.close);
}

/**
* Open + write + close as one thread pool round trip.
* @param {string|Buffer} path Validated path
* @param {number} flagsNumber
* @param {number} mode
* @param {ArrayBufferView} data
* @returns {Promise<void>}
*/
function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
return new Promise((resolve, reject) => {
const job = new binding.WriteFileJob(path, flagsNumber, mode, data);
job.ondone = (err) => {
if (err != null) {
ErrorCaptureStackTrace(err, writeFileInOneRoundTrip);
reject(err);
} else {
resolve();
}
};
const accessError = job.run(path);
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip);
reject(accessError);
}
});
}

function isCustomIterable(obj) {
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}
Expand Down
167 changes: 167 additions & 0 deletions src/node_file.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,6 +65,7 @@ namespace fs {

using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BigInt;
using v8::Context;
using v8::EscapableHandleScope;
Expand DownExpand Up@@ -3703,6 +3704,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
SET_SELF_SIZE(ReadFileJob)

private:
friend class WriteFileJob;
static constexpr size_t kUnknownSizeChunk = 64 * 1024;
static constexpr size_t kMaxReadChunk = 256 * 1024 * 1024;

Expand DownExpand Up@@ -3786,6 +3788,162 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
int fd_ = -1;
};

// Writes a whole buffer to a file in ONE thread pool round trip -- open +
// write (until everything is written) + close -- for fs.writeFile() and
// fs.promises.writeFile() with a path, which otherwise pay one round trip per
// step.
//
// JS: const job = new WriteFileJob(path, flags, mode, buffer);
// job.ondone = (err) => {...}; job.run(path);
// `err` carries the syscall that failed ('open', 'write' or 'close'); the file
// descriptor opened here is always closed.
class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
public:
static void New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
Environment* env = Environment::GetCurrent(args);
CHECK_GE(args.Length(), 4);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
CHECK(args[1]->IsInt32());
CHECK(args[2]->IsInt32());
CHECK(args[3]->IsArrayBufferView());
new WriteFileJob(env,
args.This(),
path.ToString(),
args[1].As<Int32>()->Value(),
args[2].As<Int32>()->Value(),
args[3].As<ArrayBufferView>());
}

// Returns undefined when the job was scheduled, or the ERR_ACCESS_DENIED
// error the asynchronous open() would have delivered (nothing is scheduled).
static void Run(const FunctionCallbackInfo<Value>& args) {
WriteFileJob* job;
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
Local<Value> access_error;
if (ReadFileJob::OpenPermissionError(env, path, job->flags_)
.ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
}
job->scheduled_ = true;
job->ClearWeak();
FS_ASYNC_TRACE_BEGIN0(UV_FS_WRITE, job)
job->ScheduleWork();
}

void DoThreadPoolWork() override {
uv_fs_t req;
int fd = uv_fs_open(nullptr, &req, path_.c_str(), flags_, mode_, nullptr);
uv_fs_req_cleanup(&req);
if (fd < 0) return Fail("open", fd);

size_t written = 0;
while (written < length_) {
uv_buf_t buf = uv_buf_init(data_ + written,
static_cast<unsigned int>(std::min<size_t>(
length_ - written, kMaxWriteChunk)));
int r = uv_fs_write(nullptr, &req, fd, &buf, 1, -1, nullptr);
uv_fs_req_cleanup(&req);
if (r < 0) {
Fail("write", r);
break;
}
written += static_cast<size_t>(r);
}

int rc = uv_fs_close(nullptr, &req, fd, nullptr);
uv_fs_req_cleanup(&req);
if (rc < 0 && error_ == 0) Fail("close", rc);
}

void AfterThreadPoolWork(int status) override {
Environment* env = AsyncWrap::env();
std::unique_ptr<WriteFileJob> self(this);
CHECK(status == 0 || status == UV_ECANCELED);
FS_ASYNC_TRACE_END0(UV_FS_WRITE, this)
if (status == UV_ECANCELED || !env->can_call_into_js()) return;
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Isolate* isolate = env->isolate();
Local<Value> argv[1] = {Null(isolate)};
if (error_ != 0) {
argv[0] = UVException(isolate,
error_,
syscall_,
nullptr,
syscall_ == kOpen ? path_.c_str() : nullptr);
}
MakeCallback(env->ondone_string(), arraysize(argv), argv);
}

bool IsNotIndicativeOfMemoryLeakAtExit() const override { return true; }
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("buffer", buffer_);
if (copy_) tracker->TrackFieldWithSize("copy", length_);
}
SET_MEMORY_INFO_NAME(WriteFileJob)
SET_SELF_SIZE(WriteFileJob)

private:
static constexpr size_t kMaxWriteChunk = 256 * 1024 * 1024;
static constexpr const char* kOpen = "open";

WriteFileJob(Environment* env,
Local<Object> object,
std::string&& path,
int flags,
int mode,
Local<ArrayBufferView> view)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
ThreadPoolWork(env, "fs.writefile"),
path_(std::move(path)),
flags_(flags),
mode_(mode) {
// Holding the backing store keeps the memory valid even if the buffer is
// detached or collected meanwhile; a resizable buffer can still have its
// pages decommitted by a shrink, so its contents are copied instead.
length_ = view->ByteLength();
backing_store_ = view->Buffer()->GetBackingStore();
if (backing_store_->IsResizableByUserJavaScript()) {
copy_.reset(new char[length_]);
memcpy(copy_.get(),
static_cast<char*>(backing_store_->Data()) + view->ByteOffset(),
length_);
data_ = copy_.get();
backing_store_.reset();
} else {
buffer_.Reset(env->isolate(), view);
data_ = static_cast<char*>(backing_store_->Data()) + view->ByteOffset();
}
MakeWeak();
}

void Fail(const char* syscall, int error) {
syscall_ = syscall;
error_ = error;
}

const std::string path_;
v8::Global<v8::ArrayBufferView> buffer_;
std::shared_ptr<v8::BackingStore> backing_store_;
std::unique_ptr<char[]> copy_;
char* data_ = nullptr;
size_t length_ = 0;
const int flags_;
const int mode_;
bool scheduled_ = false;
int error_ = 0;
const char* syscall_ = nullptr;
};

// Wrapper for readv(2).
//
// bytesRead = fs.readv(fd, buffers[, position], callback)
Expand DownExpand Up@@ -5103,6 +5261,13 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
SetProtoMethod(isolate, rfj, "run", ReadFileJob::Run);
SetConstructorFunction(isolate, target, "ReadFileJob", rfj);

Local<FunctionTemplate> wfj = NewFunctionTemplate(isolate, WriteFileJob::New);
wfj->InstanceTemplate()->SetInternalFieldCount(
WriteFileJob::kInternalFieldCount);
wfj->Inherit(AsyncWrap::GetConstructorTemplate(isolate_data));
SetProtoMethod(isolate, wfj, "run", WriteFileJob::Run);
SetConstructorFunction(isolate, target, "WriteFileJob", wfj);

// Create FunctionTemplate for FSReqCallback
Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback);
fst->InstanceTemplate()->SetInternalFieldCount(
Expand DownExpand Up@@ -5177,6 +5342,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Open);
registry->Register(ReadFileJob::New);
registry->Register(ReadFileJob::Run);
registry->Register(WriteFileJob::New);
registry->Register(WriteFileJob::Run);
registry->Register(OpenFileHandle);
registry->Register(Read);
registry->Register(ReadFileUtf8);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,7 +67,9 @@ async function checkAggregateError(op) {
tmpdir.refresh();
await checkAggregateError((filePath) => truncate(filePath));
await checkAggregateError((filePath) => readFile(filePath));
await checkAggregateError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkAggregateError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkAggregateError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-close-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -62,7 +62,9 @@ async function checkCloseError(op) {
tmpdir.refresh();
await checkCloseError((filePath) => truncate(filePath));
await checkCloseError((filePath) => readFile(filePath));
await checkCloseError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkCloseError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkCloseError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-op-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,7 +56,9 @@ async function checkOperationError(op) {
tmpdir.refresh();
await checkOperationError((filePath) => truncate(filePath));
await checkOperationError((filePath) => readFile(filePath));
await checkOperationError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkOperationError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkOperationError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/fs.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -79,6 +79,7 @@ const {
const {
FSReqCallback,
ReadFileJob,
WriteFileJob,
} = binding;
const { toPathIfFileURL } = require('internal/url');
const {
Expand DownExpand Up@@ -2929,6 +2930,23 @@ function writeFile(path, data, options, callback) {
if (checkAborted(options.signal, callback))
return;

if (!flush) {
// Open + write + close in one thread pool round trip.
const signal = options.signal;
path = getValidatedPath(path);
const job = new WriteFileJob(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
job.ondone = signal == null ? callback : (err) => {
// An abort that arrived while the write was in flight still wins.
callback(signal.aborted && !err ? new AbortError(undefined, { cause: signal.reason }) : err);
};
const accessError = job.run(path);
if (accessError !== undefined) {
callback(accessError);
}
return;
}

fs.open(path, flag, options.mode, (openErr, fd) => {
if (openErr) {
callback(openErr);
Expand Down
35 changes: 35 additions & 0 deletions lib/internal/fs/promises.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2116,6 +2116,14 @@ async function writeFile(path, data, options) {

checkAborted(options.signal);

if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) {
path = getValidatedPath(path);
await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
checkAborted(options.signal); // An abort during the write still wins.
return;
}

const fd = await open(path, flag, options.mode);
let writeOp = writeFileHandle(fd, data, options.signal, options.encoding);

Expand All@@ -2126,6 +2134,33 @@ async function writeFile(path, data, options) {
return handleFdClose(writeOp, fd.close);
}

/**
* Open + write + close as one thread pool round trip.
* @param {string|Buffer} path Validated path
* @param {number} flagsNumber
* @param {number} mode
* @param {ArrayBufferView} data
* @returns {Promise<void>}
*/
function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
return new Promise((resolve, reject) => {
const job = new binding.WriteFileJob(path, flagsNumber, mode, data);
job.ondone = (err) => {
if (err != null) {
ErrorCaptureStackTrace(err, writeFileInOneRoundTrip);
reject(err);
} else {
resolve();
}
};
const accessError = job.run(path);
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip);
reject(accessError);
}
});
}

function isCustomIterable(obj) {
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}
Expand Down
167 changes: 167 additions & 0 deletions src/node_file.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,6 +65,7 @@ namespace fs {

using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BigInt;
using v8::Context;
using v8::EscapableHandleScope;
Expand DownExpand Up@@ -3703,6 +3704,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
SET_SELF_SIZE(ReadFileJob)

private:
friend class WriteFileJob;
static constexpr size_t kUnknownSizeChunk = 64 * 1024;
static constexpr size_t kMaxReadChunk = 256 * 1024 * 1024;

Expand DownExpand Up@@ -3786,6 +3788,162 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
int fd_ = -1;
};

// Writes a whole buffer to a file in ONE thread pool round trip -- open +
// write (until everything is written) + close -- for fs.writeFile() and
// fs.promises.writeFile() with a path, which otherwise pay one round trip per
// step.
//
// JS: const job = new WriteFileJob(path, flags, mode, buffer);
// job.ondone = (err) => {...}; job.run(path);
// `err` carries the syscall that failed ('open', 'write' or 'close'); the file
// descriptor opened here is always closed.
class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
public:
static void New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
Environment* env = Environment::GetCurrent(args);
CHECK_GE(args.Length(), 4);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
CHECK(args[1]->IsInt32());
CHECK(args[2]->IsInt32());
CHECK(args[3]->IsArrayBufferView());
new WriteFileJob(env,
args.This(),
path.ToString(),
args[1].As<Int32>()->Value(),
args[2].As<Int32>()->Value(),
args[3].As<ArrayBufferView>());
}

// Returns undefined when the job was scheduled, or the ERR_ACCESS_DENIED
// error the asynchronous open() would have delivered (nothing is scheduled).
static void Run(const FunctionCallbackInfo<Value>& args) {
WriteFileJob* job;
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
Local<Value> access_error;
if (ReadFileJob::OpenPermissionError(env, path, job->flags_)
.ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
}
job->scheduled_ = true;
job->ClearWeak();
FS_ASYNC_TRACE_BEGIN0(UV_FS_WRITE, job)
job->ScheduleWork();
}

void DoThreadPoolWork() override {
uv_fs_t req;
int fd = uv_fs_open(nullptr, &req, path_.c_str(), flags_, mode_, nullptr);
uv_fs_req_cleanup(&req);
if (fd < 0) return Fail("open", fd);

size_t written = 0;
while (written < length_) {
uv_buf_t buf = uv_buf_init(data_ + written,
static_cast<unsigned int>(std::min<size_t>(
length_ - written, kMaxWriteChunk)));
int r = uv_fs_write(nullptr, &req, fd, &buf, 1, -1, nullptr);
uv_fs_req_cleanup(&req);
if (r < 0) {
Fail("write", r);
break;
}
written += static_cast<size_t>(r);
}

int rc = uv_fs_close(nullptr, &req, fd, nullptr);
uv_fs_req_cleanup(&req);
if (rc < 0 && error_ == 0) Fail("close", rc);
}

void AfterThreadPoolWork(int status) override {
Environment* env = AsyncWrap::env();
std::unique_ptr<WriteFileJob> self(this);
CHECK(status == 0 || status == UV_ECANCELED);
FS_ASYNC_TRACE_END0(UV_FS_WRITE, this)
if (status == UV_ECANCELED || !env->can_call_into_js()) return;
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Isolate* isolate = env->isolate();
Local<Value> argv[1] = {Null(isolate)};
if (error_ != 0) {
argv[0] = UVException(isolate,
error_,
syscall_,
nullptr,
syscall_ == kOpen ? path_.c_str() : nullptr);
}
MakeCallback(env->ondone_string(), arraysize(argv), argv);
}

bool IsNotIndicativeOfMemoryLeakAtExit() const override { return true; }
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("buffer", buffer_);
if (copy_) tracker->TrackFieldWithSize("copy", length_);
}
SET_MEMORY_INFO_NAME(WriteFileJob)
SET_SELF_SIZE(WriteFileJob)

private:
static constexpr size_t kMaxWriteChunk = 256 * 1024 * 1024;
static constexpr const char* kOpen = "open";

WriteFileJob(Environment* env,
Local<Object> object,
std::string&& path,
int flags,
int mode,
Local<ArrayBufferView> view)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
ThreadPoolWork(env, "fs.writefile"),
path_(std::move(path)),
flags_(flags),
mode_(mode) {
// Holding the backing store keeps the memory valid even if the buffer is
// detached or collected meanwhile; a resizable buffer can still have its
// pages decommitted by a shrink, so its contents are copied instead.
length_ = view->ByteLength();
backing_store_ = view->Buffer()->GetBackingStore();
if (backing_store_->IsResizableByUserJavaScript()) {
copy_.reset(new char[length_]);
memcpy(copy_.get(),
static_cast<char*>(backing_store_->Data()) + view->ByteOffset(),
length_);
data_ = copy_.get();
backing_store_.reset();
} else {
buffer_.Reset(env->isolate(), view);
data_ = static_cast<char*>(backing_store_->Data()) + view->ByteOffset();
}
MakeWeak();
}

void Fail(const char* syscall, int error) {
syscall_ = syscall;
error_ = error;
}

const std::string path_;
v8::Global<v8::ArrayBufferView> buffer_;
std::shared_ptr<v8::BackingStore> backing_store_;
std::unique_ptr<char[]> copy_;
char* data_ = nullptr;
size_t length_ = 0;
const int flags_;
const int mode_;
bool scheduled_ = false;
int error_ = 0;
const char* syscall_ = nullptr;
};

// Wrapper for readv(2).
//
// bytesRead = fs.readv(fd, buffers[, position], callback)
Expand DownExpand Up@@ -5103,6 +5261,13 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
SetProtoMethod(isolate, rfj, "run", ReadFileJob::Run);
SetConstructorFunction(isolate, target, "ReadFileJob", rfj);

Local<FunctionTemplate> wfj = NewFunctionTemplate(isolate, WriteFileJob::New);
wfj->InstanceTemplate()->SetInternalFieldCount(
WriteFileJob::kInternalFieldCount);
wfj->Inherit(AsyncWrap::GetConstructorTemplate(isolate_data));
SetProtoMethod(isolate, wfj, "run", WriteFileJob::Run);
SetConstructorFunction(isolate, target, "WriteFileJob", wfj);

// Create FunctionTemplate for FSReqCallback
Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback);
fst->InstanceTemplate()->SetInternalFieldCount(
Expand DownExpand Up@@ -5177,6 +5342,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Open);
registry->Register(ReadFileJob::New);
registry->Register(ReadFileJob::Run);
registry->Register(WriteFileJob::New);
registry->Register(WriteFileJob::Run);
registry->Register(OpenFileHandle);
registry->Register(Read);
registry->Register(ReadFileUtf8);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,7 +67,9 @@ async function checkAggregateError(op) {
tmpdir.refresh();
await checkAggregateError((filePath) => truncate(filePath));
await checkAggregateError((filePath) => readFile(filePath));
await checkAggregateError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkAggregateError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkAggregateError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-close-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -62,7 +62,9 @@ async function checkCloseError(op) {
tmpdir.refresh();
await checkCloseError((filePath) => truncate(filePath));
await checkCloseError((filePath) => readFile(filePath));
await checkCloseError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkCloseError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkCloseError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-op-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,7 +56,9 @@ async function checkOperationError(op) {
tmpdir.refresh();
await checkOperationError((filePath) => truncate(filePath));
await checkOperationError((filePath) => readFile(filePath));
await checkOperationError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkOperationError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkOperationError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/fs.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -79,6 +79,7 @@ const {
const {
FSReqCallback,
ReadFileJob,
WriteFileJob,
} = binding;
const { toPathIfFileURL } = require('internal/url');
const {
Expand DownExpand Up@@ -2929,6 +2930,23 @@ function writeFile(path, data, options, callback) {
if (checkAborted(options.signal, callback))
return;

if (!flush) {
// Open + write + close in one thread pool round trip.
const signal = options.signal;
path = getValidatedPath(path);
const job = new WriteFileJob(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
job.ondone = signal == null ? callback : (err) => {
// An abort that arrived while the write was in flight still wins.
callback(signal.aborted && !err ? new AbortError(undefined, { cause: signal.reason }) : err);
};
const accessError = job.run(path);
if (accessError !== undefined) {
callback(accessError);
}
return;
}

fs.open(path, flag, options.mode, (openErr, fd) => {
if (openErr) {
callback(openErr);
Expand Down
35 changes: 35 additions & 0 deletions lib/internal/fs/promises.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2116,6 +2116,14 @@ async function writeFile(path, data, options) {

checkAborted(options.signal);

if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) {
path = getValidatedPath(path);
await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
checkAborted(options.signal); // An abort during the write still wins.
return;
}

const fd = await open(path, flag, options.mode);
let writeOp = writeFileHandle(fd, data, options.signal, options.encoding);

Expand All@@ -2126,6 +2134,33 @@ async function writeFile(path, data, options) {
return handleFdClose(writeOp, fd.close);
}

/**
* Open + write + close as one thread pool round trip.
* @param {string|Buffer} path Validated path
* @param {number} flagsNumber
* @param {number} mode
* @param {ArrayBufferView} data
* @returns {Promise<void>}
*/
function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
return new Promise((resolve, reject) => {
const job = new binding.WriteFileJob(path, flagsNumber, mode, data);
job.ondone = (err) => {
if (err != null) {
ErrorCaptureStackTrace(err, writeFileInOneRoundTrip);
reject(err);
} else {
resolve();
}
};
const accessError = job.run(path);
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip);
reject(accessError);
}
});
}

function isCustomIterable(obj) {
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}
Expand Down
167 changes: 167 additions & 0 deletions src/node_file.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,6 +65,7 @@ namespace fs {

using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BigInt;
using v8::Context;
using v8::EscapableHandleScope;
Expand DownExpand Up@@ -3703,6 +3704,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
SET_SELF_SIZE(ReadFileJob)

private:
friend class WriteFileJob;
static constexpr size_t kUnknownSizeChunk = 64 * 1024;
static constexpr size_t kMaxReadChunk = 256 * 1024 * 1024;

Expand DownExpand Up@@ -3786,6 +3788,162 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
int fd_ = -1;
};

// Writes a whole buffer to a file in ONE thread pool round trip -- open +
// write (until everything is written) + close -- for fs.writeFile() and
// fs.promises.writeFile() with a path, which otherwise pay one round trip per
// step.
//
// JS: const job = new WriteFileJob(path, flags, mode, buffer);
// job.ondone = (err) => {...}; job.run(path);
// `err` carries the syscall that failed ('open', 'write' or 'close'); the file
// descriptor opened here is always closed.
class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
public:
static void New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
Environment* env = Environment::GetCurrent(args);
CHECK_GE(args.Length(), 4);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
CHECK(args[1]->IsInt32());
CHECK(args[2]->IsInt32());
CHECK(args[3]->IsArrayBufferView());
new WriteFileJob(env,
args.This(),
path.ToString(),
args[1].As<Int32>()->Value(),
args[2].As<Int32>()->Value(),
args[3].As<ArrayBufferView>());
}

// Returns undefined when the job was scheduled, or the ERR_ACCESS_DENIED
// error the asynchronous open() would have delivered (nothing is scheduled).
static void Run(const FunctionCallbackInfo<Value>& args) {
WriteFileJob* job;
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
Local<Value> access_error;
if (ReadFileJob::OpenPermissionError(env, path, job->flags_)
.ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
}
job->scheduled_ = true;
job->ClearWeak();
FS_ASYNC_TRACE_BEGIN0(UV_FS_WRITE, job)
job->ScheduleWork();
}

void DoThreadPoolWork() override {
uv_fs_t req;
int fd = uv_fs_open(nullptr, &req, path_.c_str(), flags_, mode_, nullptr);
uv_fs_req_cleanup(&req);
if (fd < 0) return Fail("open", fd);

size_t written = 0;
while (written < length_) {
uv_buf_t buf = uv_buf_init(data_ + written,
static_cast<unsigned int>(std::min<size_t>(
length_ - written, kMaxWriteChunk)));
int r = uv_fs_write(nullptr, &req, fd, &buf, 1, -1, nullptr);
uv_fs_req_cleanup(&req);
if (r < 0) {
Fail("write", r);
break;
}
written += static_cast<size_t>(r);
}

int rc = uv_fs_close(nullptr, &req, fd, nullptr);
uv_fs_req_cleanup(&req);
if (rc < 0 && error_ == 0) Fail("close", rc);
}

void AfterThreadPoolWork(int status) override {
Environment* env = AsyncWrap::env();
std::unique_ptr<WriteFileJob> self(this);
CHECK(status == 0 || status == UV_ECANCELED);
FS_ASYNC_TRACE_END0(UV_FS_WRITE, this)
if (status == UV_ECANCELED || !env->can_call_into_js()) return;
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Isolate* isolate = env->isolate();
Local<Value> argv[1] = {Null(isolate)};
if (error_ != 0) {
argv[0] = UVException(isolate,
error_,
syscall_,
nullptr,
syscall_ == kOpen ? path_.c_str() : nullptr);
}
MakeCallback(env->ondone_string(), arraysize(argv), argv);
}

bool IsNotIndicativeOfMemoryLeakAtExit() const override { return true; }
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("buffer", buffer_);
if (copy_) tracker->TrackFieldWithSize("copy", length_);
}
SET_MEMORY_INFO_NAME(WriteFileJob)
SET_SELF_SIZE(WriteFileJob)

private:
static constexpr size_t kMaxWriteChunk = 256 * 1024 * 1024;
static constexpr const char* kOpen = "open";

WriteFileJob(Environment* env,
Local<Object> object,
std::string&& path,
int flags,
int mode,
Local<ArrayBufferView> view)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
ThreadPoolWork(env, "fs.writefile"),
path_(std::move(path)),
flags_(flags),
mode_(mode) {
// Holding the backing store keeps the memory valid even if the buffer is
// detached or collected meanwhile; a resizable buffer can still have its
// pages decommitted by a shrink, so its contents are copied instead.
length_ = view->ByteLength();
backing_store_ = view->Buffer()->GetBackingStore();
if (backing_store_->IsResizableByUserJavaScript()) {
copy_.reset(new char[length_]);
memcpy(copy_.get(),
static_cast<char*>(backing_store_->Data()) + view->ByteOffset(),
length_);
data_ = copy_.get();
backing_store_.reset();
} else {
buffer_.Reset(env->isolate(), view);
data_ = static_cast<char*>(backing_store_->Data()) + view->ByteOffset();
}
MakeWeak();
}

void Fail(const char* syscall, int error) {
syscall_ = syscall;
error_ = error;
}

const std::string path_;
v8::Global<v8::ArrayBufferView> buffer_;
std::shared_ptr<v8::BackingStore> backing_store_;
std::unique_ptr<char[]> copy_;
char* data_ = nullptr;
size_t length_ = 0;
const int flags_;
const int mode_;
bool scheduled_ = false;
int error_ = 0;
const char* syscall_ = nullptr;
};

// Wrapper for readv(2).
//
// bytesRead = fs.readv(fd, buffers[, position], callback)
Expand DownExpand Up@@ -5103,6 +5261,13 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
SetProtoMethod(isolate, rfj, "run", ReadFileJob::Run);
SetConstructorFunction(isolate, target, "ReadFileJob", rfj);

Local<FunctionTemplate> wfj = NewFunctionTemplate(isolate, WriteFileJob::New);
wfj->InstanceTemplate()->SetInternalFieldCount(
WriteFileJob::kInternalFieldCount);
wfj->Inherit(AsyncWrap::GetConstructorTemplate(isolate_data));
SetProtoMethod(isolate, wfj, "run", WriteFileJob::Run);
SetConstructorFunction(isolate, target, "WriteFileJob", wfj);

// Create FunctionTemplate for FSReqCallback
Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback);
fst->InstanceTemplate()->SetInternalFieldCount(
Expand DownExpand Up@@ -5177,6 +5342,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Open);
registry->Register(ReadFileJob::New);
registry->Register(ReadFileJob::Run);
registry->Register(WriteFileJob::New);
registry->Register(WriteFileJob::Run);
registry->Register(OpenFileHandle);
registry->Register(Read);
registry->Register(ReadFileUtf8);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,7 +67,9 @@ async function checkAggregateError(op) {
tmpdir.refresh();
await checkAggregateError((filePath) => truncate(filePath));
await checkAggregateError((filePath) => readFile(filePath));
await checkAggregateError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkAggregateError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkAggregateError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-close-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -62,7 +62,9 @@ async function checkCloseError(op) {
tmpdir.refresh();
await checkCloseError((filePath) => truncate(filePath));
await checkCloseError((filePath) => readFile(filePath));
await checkCloseError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkCloseError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkCloseError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-op-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,7 +56,9 @@ async function checkOperationError(op) {
tmpdir.refresh();
await checkOperationError((filePath) => truncate(filePath));
await checkOperationError((filePath) => readFile(filePath));
await checkOperationError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkOperationError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkOperationError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/fs.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -79,6 +79,7 @@ const {
const {
FSReqCallback,
ReadFileJob,
WriteFileJob,
} = binding;
const { toPathIfFileURL } = require('internal/url');
const {
Expand DownExpand Up@@ -2929,6 +2930,23 @@ function writeFile(path, data, options, callback) {
if (checkAborted(options.signal, callback))
return;

if (!flush) {
// Open + write + close in one thread pool round trip.
const signal = options.signal;
path = getValidatedPath(path);
const job = new WriteFileJob(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
job.ondone = signal == null ? callback : (err) => {
// An abort that arrived while the write was in flight still wins.
callback(signal.aborted && !err ? new AbortError(undefined, { cause: signal.reason }) : err);
};
const accessError = job.run(path);
if (accessError !== undefined) {
callback(accessError);
}
return;
}

fs.open(path, flag, options.mode, (openErr, fd) => {
if (openErr) {
callback(openErr);
Expand Down
35 changes: 35 additions & 0 deletions lib/internal/fs/promises.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2116,6 +2116,14 @@ async function writeFile(path, data, options) {

checkAborted(options.signal);

if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) {
path = getValidatedPath(path);
await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
checkAborted(options.signal); // An abort during the write still wins.
return;
}

const fd = await open(path, flag, options.mode);
let writeOp = writeFileHandle(fd, data, options.signal, options.encoding);

Expand All@@ -2126,6 +2134,33 @@ async function writeFile(path, data, options) {
return handleFdClose(writeOp, fd.close);
}

/**
* Open + write + close as one thread pool round trip.
* @param {string|Buffer} path Validated path
* @param {number} flagsNumber
* @param {number} mode
* @param {ArrayBufferView} data
* @returns {Promise<void>}
*/
function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
return new Promise((resolve, reject) => {
const job = new binding.WriteFileJob(path, flagsNumber, mode, data);
job.ondone = (err) => {
if (err != null) {
ErrorCaptureStackTrace(err, writeFileInOneRoundTrip);
reject(err);
} else {
resolve();
}
};
const accessError = job.run(path);
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip);
reject(accessError);
}
});
}

function isCustomIterable(obj) {
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}
Expand Down
167 changes: 167 additions & 0 deletions src/node_file.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,6 +65,7 @@ namespace fs {

using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BigInt;
using v8::Context;
using v8::EscapableHandleScope;
Expand DownExpand Up@@ -3703,6 +3704,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
SET_SELF_SIZE(ReadFileJob)

private:
friend class WriteFileJob;
static constexpr size_t kUnknownSizeChunk = 64 * 1024;
static constexpr size_t kMaxReadChunk = 256 * 1024 * 1024;

Expand DownExpand Up@@ -3786,6 +3788,162 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
int fd_ = -1;
};

// Writes a whole buffer to a file in ONE thread pool round trip -- open +
// write (until everything is written) + close -- for fs.writeFile() and
// fs.promises.writeFile() with a path, which otherwise pay one round trip per
// step.
//
// JS: const job = new WriteFileJob(path, flags, mode, buffer);
// job.ondone = (err) => {...}; job.run(path);
// `err` carries the syscall that failed ('open', 'write' or 'close'); the file
// descriptor opened here is always closed.
class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
public:
static void New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
Environment* env = Environment::GetCurrent(args);
CHECK_GE(args.Length(), 4);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
CHECK(args[1]->IsInt32());
CHECK(args[2]->IsInt32());
CHECK(args[3]->IsArrayBufferView());
new WriteFileJob(env,
args.This(),
path.ToString(),
args[1].As<Int32>()->Value(),
args[2].As<Int32>()->Value(),
args[3].As<ArrayBufferView>());
}

// Returns undefined when the job was scheduled, or the ERR_ACCESS_DENIED
// error the asynchronous open() would have delivered (nothing is scheduled).
static void Run(const FunctionCallbackInfo<Value>& args) {
WriteFileJob* job;
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
Local<Value> access_error;
if (ReadFileJob::OpenPermissionError(env, path, job->flags_)
.ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
}
job->scheduled_ = true;
job->ClearWeak();
FS_ASYNC_TRACE_BEGIN0(UV_FS_WRITE, job)
job->ScheduleWork();
}

void DoThreadPoolWork() override {
uv_fs_t req;
int fd = uv_fs_open(nullptr, &req, path_.c_str(), flags_, mode_, nullptr);
uv_fs_req_cleanup(&req);
if (fd < 0) return Fail("open", fd);

size_t written = 0;
while (written < length_) {
uv_buf_t buf = uv_buf_init(data_ + written,
static_cast<unsigned int>(std::min<size_t>(
length_ - written, kMaxWriteChunk)));
int r = uv_fs_write(nullptr, &req, fd, &buf, 1, -1, nullptr);
uv_fs_req_cleanup(&req);
if (r < 0) {
Fail("write", r);
break;
}
written += static_cast<size_t>(r);
}

int rc = uv_fs_close(nullptr, &req, fd, nullptr);
uv_fs_req_cleanup(&req);
if (rc < 0 && error_ == 0) Fail("close", rc);
}

void AfterThreadPoolWork(int status) override {
Environment* env = AsyncWrap::env();
std::unique_ptr<WriteFileJob> self(this);
CHECK(status == 0 || status == UV_ECANCELED);
FS_ASYNC_TRACE_END0(UV_FS_WRITE, this)
if (status == UV_ECANCELED || !env->can_call_into_js()) return;
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Isolate* isolate = env->isolate();
Local<Value> argv[1] = {Null(isolate)};
if (error_ != 0) {
argv[0] = UVException(isolate,
error_,
syscall_,
nullptr,
syscall_ == kOpen ? path_.c_str() : nullptr);
}
MakeCallback(env->ondone_string(), arraysize(argv), argv);
}

bool IsNotIndicativeOfMemoryLeakAtExit() const override { return true; }
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("buffer", buffer_);
if (copy_) tracker->TrackFieldWithSize("copy", length_);
}
SET_MEMORY_INFO_NAME(WriteFileJob)
SET_SELF_SIZE(WriteFileJob)

private:
static constexpr size_t kMaxWriteChunk = 256 * 1024 * 1024;
static constexpr const char* kOpen = "open";

WriteFileJob(Environment* env,
Local<Object> object,
std::string&& path,
int flags,
int mode,
Local<ArrayBufferView> view)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
ThreadPoolWork(env, "fs.writefile"),
path_(std::move(path)),
flags_(flags),
mode_(mode) {
// Holding the backing store keeps the memory valid even if the buffer is
// detached or collected meanwhile; a resizable buffer can still have its
// pages decommitted by a shrink, so its contents are copied instead.
length_ = view->ByteLength();
backing_store_ = view->Buffer()->GetBackingStore();
if (backing_store_->IsResizableByUserJavaScript()) {
copy_.reset(new char[length_]);
memcpy(copy_.get(),
static_cast<char*>(backing_store_->Data()) + view->ByteOffset(),
length_);
data_ = copy_.get();
backing_store_.reset();
} else {
buffer_.Reset(env->isolate(), view);
data_ = static_cast<char*>(backing_store_->Data()) + view->ByteOffset();
}
MakeWeak();
}

void Fail(const char* syscall, int error) {
syscall_ = syscall;
error_ = error;
}

const std::string path_;
v8::Global<v8::ArrayBufferView> buffer_;
std::shared_ptr<v8::BackingStore> backing_store_;
std::unique_ptr<char[]> copy_;
char* data_ = nullptr;
size_t length_ = 0;
const int flags_;
const int mode_;
bool scheduled_ = false;
int error_ = 0;
const char* syscall_ = nullptr;
};

// Wrapper for readv(2).
//
// bytesRead = fs.readv(fd, buffers[, position], callback)
Expand DownExpand Up@@ -5103,6 +5261,13 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
SetProtoMethod(isolate, rfj, "run", ReadFileJob::Run);
SetConstructorFunction(isolate, target, "ReadFileJob", rfj);

Local<FunctionTemplate> wfj = NewFunctionTemplate(isolate, WriteFileJob::New);
wfj->InstanceTemplate()->SetInternalFieldCount(
WriteFileJob::kInternalFieldCount);
wfj->Inherit(AsyncWrap::GetConstructorTemplate(isolate_data));
SetProtoMethod(isolate, wfj, "run", WriteFileJob::Run);
SetConstructorFunction(isolate, target, "WriteFileJob", wfj);

// Create FunctionTemplate for FSReqCallback
Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback);
fst->InstanceTemplate()->SetInternalFieldCount(
Expand DownExpand Up@@ -5177,6 +5342,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Open);
registry->Register(ReadFileJob::New);
registry->Register(ReadFileJob::Run);
registry->Register(WriteFileJob::New);
registry->Register(WriteFileJob::Run);
registry->Register(OpenFileHandle);
registry->Register(Read);
registry->Register(ReadFileUtf8);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,7 +67,9 @@ async function checkAggregateError(op) {
tmpdir.refresh();
await checkAggregateError((filePath) => truncate(filePath));
await checkAggregateError((filePath) => readFile(filePath));
await checkAggregateError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkAggregateError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkAggregateError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-close-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -62,7 +62,9 @@ async function checkCloseError(op) {
tmpdir.refresh();
await checkCloseError((filePath) => truncate(filePath));
await checkCloseError((filePath) => readFile(filePath));
await checkCloseError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkCloseError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkCloseError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-op-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,7 +56,9 @@ async function checkOperationError(op) {
tmpdir.refresh();
await checkOperationError((filePath) => truncate(filePath));
await checkOperationError((filePath) => readFile(filePath));
await checkOperationError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkOperationError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkOperationError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/fs.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -79,6 +79,7 @@ const {
const {
FSReqCallback,
ReadFileJob,
WriteFileJob,
} = binding;
const { toPathIfFileURL } = require('internal/url');
const {
Expand DownExpand Up@@ -2929,6 +2930,23 @@ function writeFile(path, data, options, callback) {
if (checkAborted(options.signal, callback))
return;

if (!flush) {
// Open + write + close in one thread pool round trip.
const signal = options.signal;
path = getValidatedPath(path);
const job = new WriteFileJob(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
job.ondone = signal == null ? callback : (err) => {
// An abort that arrived while the write was in flight still wins.
callback(signal.aborted && !err ? new AbortError(undefined, { cause: signal.reason }) : err);
};
const accessError = job.run(path);
if (accessError !== undefined) {
callback(accessError);
}
return;
}

fs.open(path, flag, options.mode, (openErr, fd) => {
if (openErr) {
callback(openErr);
Expand Down
35 changes: 35 additions & 0 deletions lib/internal/fs/promises.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2116,6 +2116,14 @@ async function writeFile(path, data, options) {

checkAborted(options.signal);

if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) {
path = getValidatedPath(path);
await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
checkAborted(options.signal); // An abort during the write still wins.
return;
}

const fd = await open(path, flag, options.mode);
let writeOp = writeFileHandle(fd, data, options.signal, options.encoding);

Expand All@@ -2126,6 +2134,33 @@ async function writeFile(path, data, options) {
return handleFdClose(writeOp, fd.close);
}

/**
* Open + write + close as one thread pool round trip.
* @param {string|Buffer} path Validated path
* @param {number} flagsNumber
* @param {number} mode
* @param {ArrayBufferView} data
* @returns {Promise<void>}
*/
function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
return new Promise((resolve, reject) => {
const job = new binding.WriteFileJob(path, flagsNumber, mode, data);
job.ondone = (err) => {
if (err != null) {
ErrorCaptureStackTrace(err, writeFileInOneRoundTrip);
reject(err);
} else {
resolve();
}
};
const accessError = job.run(path);
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip);
reject(accessError);
}
});
}

function isCustomIterable(obj) {
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}
Expand Down
167 changes: 167 additions & 0 deletions src/node_file.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,6 +65,7 @@ namespace fs {

using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BigInt;
using v8::Context;
using v8::EscapableHandleScope;
Expand DownExpand Up@@ -3703,6 +3704,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
SET_SELF_SIZE(ReadFileJob)

private:
friend class WriteFileJob;
static constexpr size_t kUnknownSizeChunk = 64 * 1024;
static constexpr size_t kMaxReadChunk = 256 * 1024 * 1024;

Expand DownExpand Up@@ -3786,6 +3788,162 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
int fd_ = -1;
};

// Writes a whole buffer to a file in ONE thread pool round trip -- open +
// write (until everything is written) + close -- for fs.writeFile() and
// fs.promises.writeFile() with a path, which otherwise pay one round trip per
// step.
//
// JS: const job = new WriteFileJob(path, flags, mode, buffer);
// job.ondone = (err) => {...}; job.run(path);
// `err` carries the syscall that failed ('open', 'write' or 'close'); the file
// descriptor opened here is always closed.
class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
public:
static void New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
Environment* env = Environment::GetCurrent(args);
CHECK_GE(args.Length(), 4);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
CHECK(args[1]->IsInt32());
CHECK(args[2]->IsInt32());
CHECK(args[3]->IsArrayBufferView());
new WriteFileJob(env,
args.This(),
path.ToString(),
args[1].As<Int32>()->Value(),
args[2].As<Int32>()->Value(),
args[3].As<ArrayBufferView>());
}

// Returns undefined when the job was scheduled, or the ERR_ACCESS_DENIED
// error the asynchronous open() would have delivered (nothing is scheduled).
static void Run(const FunctionCallbackInfo<Value>& args) {
WriteFileJob* job;
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
Local<Value> access_error;
if (ReadFileJob::OpenPermissionError(env, path, job->flags_)
.ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
}
job->scheduled_ = true;
job->ClearWeak();
FS_ASYNC_TRACE_BEGIN0(UV_FS_WRITE, job)
job->ScheduleWork();
}

void DoThreadPoolWork() override {
uv_fs_t req;
int fd = uv_fs_open(nullptr, &req, path_.c_str(), flags_, mode_, nullptr);
uv_fs_req_cleanup(&req);
if (fd < 0) return Fail("open", fd);

size_t written = 0;
while (written < length_) {
uv_buf_t buf = uv_buf_init(data_ + written,
static_cast<unsigned int>(std::min<size_t>(
length_ - written, kMaxWriteChunk)));
int r = uv_fs_write(nullptr, &req, fd, &buf, 1, -1, nullptr);
uv_fs_req_cleanup(&req);
if (r < 0) {
Fail("write", r);
break;
}
written += static_cast<size_t>(r);
}

int rc = uv_fs_close(nullptr, &req, fd, nullptr);
uv_fs_req_cleanup(&req);
if (rc < 0 && error_ == 0) Fail("close", rc);
}

void AfterThreadPoolWork(int status) override {
Environment* env = AsyncWrap::env();
std::unique_ptr<WriteFileJob> self(this);
CHECK(status == 0 || status == UV_ECANCELED);
FS_ASYNC_TRACE_END0(UV_FS_WRITE, this)
if (status == UV_ECANCELED || !env->can_call_into_js()) return;
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Isolate* isolate = env->isolate();
Local<Value> argv[1] = {Null(isolate)};
if (error_ != 0) {
argv[0] = UVException(isolate,
error_,
syscall_,
nullptr,
syscall_ == kOpen ? path_.c_str() : nullptr);
}
MakeCallback(env->ondone_string(), arraysize(argv), argv);
}

bool IsNotIndicativeOfMemoryLeakAtExit() const override { return true; }
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("buffer", buffer_);
if (copy_) tracker->TrackFieldWithSize("copy", length_);
}
SET_MEMORY_INFO_NAME(WriteFileJob)
SET_SELF_SIZE(WriteFileJob)

private:
static constexpr size_t kMaxWriteChunk = 256 * 1024 * 1024;
static constexpr const char* kOpen = "open";

WriteFileJob(Environment* env,
Local<Object> object,
std::string&& path,
int flags,
int mode,
Local<ArrayBufferView> view)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
ThreadPoolWork(env, "fs.writefile"),
path_(std::move(path)),
flags_(flags),
mode_(mode) {
// Holding the backing store keeps the memory valid even if the buffer is
// detached or collected meanwhile; a resizable buffer can still have its
// pages decommitted by a shrink, so its contents are copied instead.
length_ = view->ByteLength();
backing_store_ = view->Buffer()->GetBackingStore();
if (backing_store_->IsResizableByUserJavaScript()) {
copy_.reset(new char[length_]);
memcpy(copy_.get(),
static_cast<char*>(backing_store_->Data()) + view->ByteOffset(),
length_);
data_ = copy_.get();
backing_store_.reset();
} else {
buffer_.Reset(env->isolate(), view);
data_ = static_cast<char*>(backing_store_->Data()) + view->ByteOffset();
}
MakeWeak();
}

void Fail(const char* syscall, int error) {
syscall_ = syscall;
error_ = error;
}

const std::string path_;
v8::Global<v8::ArrayBufferView> buffer_;
std::shared_ptr<v8::BackingStore> backing_store_;
std::unique_ptr<char[]> copy_;
char* data_ = nullptr;
size_t length_ = 0;
const int flags_;
const int mode_;
bool scheduled_ = false;
int error_ = 0;
const char* syscall_ = nullptr;
};

// Wrapper for readv(2).
//
// bytesRead = fs.readv(fd, buffers[, position], callback)
Expand DownExpand Up@@ -5103,6 +5261,13 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
SetProtoMethod(isolate, rfj, "run", ReadFileJob::Run);
SetConstructorFunction(isolate, target, "ReadFileJob", rfj);

Local<FunctionTemplate> wfj = NewFunctionTemplate(isolate, WriteFileJob::New);
wfj->InstanceTemplate()->SetInternalFieldCount(
WriteFileJob::kInternalFieldCount);
wfj->Inherit(AsyncWrap::GetConstructorTemplate(isolate_data));
SetProtoMethod(isolate, wfj, "run", WriteFileJob::Run);
SetConstructorFunction(isolate, target, "WriteFileJob", wfj);

// Create FunctionTemplate for FSReqCallback
Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback);
fst->InstanceTemplate()->SetInternalFieldCount(
Expand DownExpand Up@@ -5177,6 +5342,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Open);
registry->Register(ReadFileJob::New);
registry->Register(ReadFileJob::Run);
registry->Register(WriteFileJob::New);
registry->Register(WriteFileJob::Run);
registry->Register(OpenFileHandle);
registry->Register(Read);
registry->Register(ReadFileUtf8);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,7 +67,9 @@ async function checkAggregateError(op) {
tmpdir.refresh();
await checkAggregateError((filePath) => truncate(filePath));
await checkAggregateError((filePath) => readFile(filePath));
await checkAggregateError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkAggregateError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkAggregateError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-close-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -62,7 +62,9 @@ async function checkCloseError(op) {
tmpdir.refresh();
await checkCloseError((filePath) => truncate(filePath));
await checkCloseError((filePath) => readFile(filePath));
await checkCloseError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkCloseError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkCloseError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-op-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,7 +56,9 @@ async function checkOperationError(op) {
tmpdir.refresh();
await checkOperationError((filePath) => truncate(filePath));
await checkOperationError((filePath) => readFile(filePath));
await checkOperationError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkOperationError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkOperationError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions lib/fs.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -79,6 +79,7 @@ const {
const {
FSReqCallback,
ReadFileJob,
WriteFileJob,
} = binding;
const { toPathIfFileURL } = require('internal/url');
const {
Expand DownExpand Up@@ -2929,6 +2930,23 @@ function writeFile(path, data, options, callback) {
if (checkAborted(options.signal, callback))
return;

if (!flush) {
// Open + write + close in one thread pool round trip.
const signal = options.signal;
path = getValidatedPath(path);
const job = new WriteFileJob(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
job.ondone = signal == null ? callback : (err) => {
// An abort that arrived while the write was in flight still wins.
callback(signal.aborted && !err ? new AbortError(undefined, { cause: signal.reason }) : err);
};
const accessError = job.run(path);
if (accessError !== undefined) {
callback(accessError);
}
return;
}

fs.open(path, flag, options.mode, (openErr, fd) => {
if (openErr) {
callback(openErr);
Expand Down
35 changes: 35 additions & 0 deletions lib/internal/fs/promises.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -2116,6 +2116,14 @@ async function writeFile(path, data, options) {

checkAborted(options.signal);

if (!flush && !isCustomIterable(data) && data.byteLength <= kWriteFileMaxChunkSize) {
path = getValidatedPath(path);
await writeFileInOneRoundTrip(path, stringToFlags(flag, 'options.flag'),
parseFileMode(options.mode, 'mode', 0o666), data);
checkAborted(options.signal); // An abort during the write still wins.
return;
}

const fd = await open(path, flag, options.mode);
let writeOp = writeFileHandle(fd, data, options.signal, options.encoding);

Expand All@@ -2126,6 +2134,33 @@ async function writeFile(path, data, options) {
return handleFdClose(writeOp, fd.close);
}

/**
* Open + write + close as one thread pool round trip.
* @param {string|Buffer} path Validated path
* @param {number} flagsNumber
* @param {number} mode
* @param {ArrayBufferView} data
* @returns {Promise<void>}
*/
function writeFileInOneRoundTrip(path, flagsNumber, mode, data) {
return new Promise((resolve, reject) => {
const job = new binding.WriteFileJob(path, flagsNumber, mode, data);
job.ondone = (err) => {
if (err != null) {
ErrorCaptureStackTrace(err, writeFileInOneRoundTrip);
reject(err);
} else {
resolve();
}
};
const accessError = job.run(path);
if (accessError !== undefined) {
ErrorCaptureStackTrace(accessError, writeFileInOneRoundTrip);
reject(accessError);
}
});
}

function isCustomIterable(obj) {
return isIterable(obj) && !isArrayBufferView(obj) && typeof obj !== 'string';
}
Expand Down
167 changes: 167 additions & 0 deletions src/node_file.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -65,6 +65,7 @@ namespace fs {

using v8::Array;
using v8::ArrayBuffer;
using v8::ArrayBufferView;
using v8::BigInt;
using v8::Context;
using v8::EscapableHandleScope;
Expand DownExpand Up@@ -3703,6 +3704,7 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
SET_SELF_SIZE(ReadFileJob)

private:
friend class WriteFileJob;
static constexpr size_t kUnknownSizeChunk = 64 * 1024;
static constexpr size_t kMaxReadChunk = 256 * 1024 * 1024;

Expand DownExpand Up@@ -3786,6 +3788,162 @@ class ReadFileJob final : public AsyncWrap, public ThreadPoolWork {
int fd_ = -1;
};

// Writes a whole buffer to a file in ONE thread pool round trip -- open +
// write (until everything is written) + close -- for fs.writeFile() and
// fs.promises.writeFile() with a path, which otherwise pay one round trip per
// step.
//
// JS: const job = new WriteFileJob(path, flags, mode, buffer);
// job.ondone = (err) => {...}; job.run(path);
// `err` carries the syscall that failed ('open', 'write' or 'close'); the file
// descriptor opened here is always closed.
class WriteFileJob final : public AsyncWrap, public ThreadPoolWork {
public:
static void New(const FunctionCallbackInfo<Value>& args) {
CHECK(args.IsConstructCall());
Environment* env = Environment::GetCurrent(args);
CHECK_GE(args.Length(), 4);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
CHECK(args[1]->IsInt32());
CHECK(args[2]->IsInt32());
CHECK(args[3]->IsArrayBufferView());
new WriteFileJob(env,
args.This(),
path.ToString(),
args[1].As<Int32>()->Value(),
args[2].As<Int32>()->Value(),
args[3].As<ArrayBufferView>());
}

// Returns undefined when the job was scheduled, or the ERR_ACCESS_DENIED
// error the asynchronous open() would have delivered (nothing is scheduled).
static void Run(const FunctionCallbackInfo<Value>& args) {
WriteFileJob* job;
ASSIGN_OR_RETURN_UNWRAP(&job, args.This());
Environment* env = job->AsyncWrap::env();
CHECK(!job->scheduled_);
BufferValue path(env->isolate(), args[0]);
CHECK_NOT_NULL(*path);
ToNamespacedPath(env, &path);
Local<Value> access_error;
if (ReadFileJob::OpenPermissionError(env, path, job->flags_)
.ToLocal(&access_error)) {
args.GetReturnValue().Set(access_error);
return;
}
job->scheduled_ = true;
job->ClearWeak();
FS_ASYNC_TRACE_BEGIN0(UV_FS_WRITE, job)
job->ScheduleWork();
}

void DoThreadPoolWork() override {
uv_fs_t req;
int fd = uv_fs_open(nullptr, &req, path_.c_str(), flags_, mode_, nullptr);
uv_fs_req_cleanup(&req);
if (fd < 0) return Fail("open", fd);

size_t written = 0;
while (written < length_) {
uv_buf_t buf = uv_buf_init(data_ + written,
static_cast<unsigned int>(std::min<size_t>(
length_ - written, kMaxWriteChunk)));
int r = uv_fs_write(nullptr, &req, fd, &buf, 1, -1, nullptr);
uv_fs_req_cleanup(&req);
if (r < 0) {
Fail("write", r);
break;
}
written += static_cast<size_t>(r);
}

int rc = uv_fs_close(nullptr, &req, fd, nullptr);
uv_fs_req_cleanup(&req);
if (rc < 0 && error_ == 0) Fail("close", rc);
}

void AfterThreadPoolWork(int status) override {
Environment* env = AsyncWrap::env();
std::unique_ptr<WriteFileJob> self(this);
CHECK(status == 0 || status == UV_ECANCELED);
FS_ASYNC_TRACE_END0(UV_FS_WRITE, this)
if (status == UV_ECANCELED || !env->can_call_into_js()) return;
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
Isolate* isolate = env->isolate();
Local<Value> argv[1] = {Null(isolate)};
if (error_ != 0) {
argv[0] = UVException(isolate,
error_,
syscall_,
nullptr,
syscall_ == kOpen ? path_.c_str() : nullptr);
}
MakeCallback(env->ondone_string(), arraysize(argv), argv);
}

bool IsNotIndicativeOfMemoryLeakAtExit() const override { return true; }
void MemoryInfo(MemoryTracker* tracker) const override {
tracker->TrackField("buffer", buffer_);
if (copy_) tracker->TrackFieldWithSize("copy", length_);
}
SET_MEMORY_INFO_NAME(WriteFileJob)
SET_SELF_SIZE(WriteFileJob)

private:
static constexpr size_t kMaxWriteChunk = 256 * 1024 * 1024;
static constexpr const char* kOpen = "open";

WriteFileJob(Environment* env,
Local<Object> object,
std::string&& path,
int flags,
int mode,
Local<ArrayBufferView> view)
: AsyncWrap(env, object, AsyncWrap::PROVIDER_FSREQCALLBACK),
ThreadPoolWork(env, "fs.writefile"),
path_(std::move(path)),
flags_(flags),
mode_(mode) {
// Holding the backing store keeps the memory valid even if the buffer is
// detached or collected meanwhile; a resizable buffer can still have its
// pages decommitted by a shrink, so its contents are copied instead.
length_ = view->ByteLength();
backing_store_ = view->Buffer()->GetBackingStore();
if (backing_store_->IsResizableByUserJavaScript()) {
copy_.reset(new char[length_]);
memcpy(copy_.get(),
static_cast<char*>(backing_store_->Data()) + view->ByteOffset(),
length_);
data_ = copy_.get();
backing_store_.reset();
} else {
buffer_.Reset(env->isolate(), view);
data_ = static_cast<char*>(backing_store_->Data()) + view->ByteOffset();
}
MakeWeak();
}

void Fail(const char* syscall, int error) {
syscall_ = syscall;
error_ = error;
}

const std::string path_;
v8::Global<v8::ArrayBufferView> buffer_;
std::shared_ptr<v8::BackingStore> backing_store_;
std::unique_ptr<char[]> copy_;
char* data_ = nullptr;
size_t length_ = 0;
const int flags_;
const int mode_;
bool scheduled_ = false;
int error_ = 0;
const char* syscall_ = nullptr;
};

// Wrapper for readv(2).
//
// bytesRead = fs.readv(fd, buffers[, position], callback)
Expand DownExpand Up@@ -5103,6 +5261,13 @@ static void CreatePerIsolateProperties(IsolateData* isolate_data,
SetProtoMethod(isolate, rfj, "run", ReadFileJob::Run);
SetConstructorFunction(isolate, target, "ReadFileJob", rfj);

Local<FunctionTemplate> wfj = NewFunctionTemplate(isolate, WriteFileJob::New);
wfj->InstanceTemplate()->SetInternalFieldCount(
WriteFileJob::kInternalFieldCount);
wfj->Inherit(AsyncWrap::GetConstructorTemplate(isolate_data));
SetProtoMethod(isolate, wfj, "run", WriteFileJob::Run);
SetConstructorFunction(isolate, target, "WriteFileJob", wfj);

// Create FunctionTemplate for FSReqCallback
Local<FunctionTemplate> fst = NewFunctionTemplate(isolate, NewFSReqCallback);
fst->InstanceTemplate()->SetInternalFieldCount(
Expand DownExpand Up@@ -5177,6 +5342,8 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(Open);
registry->Register(ReadFileJob::New);
registry->Register(ReadFileJob::Run);
registry->Register(WriteFileJob::New);
registry->Register(WriteFileJob::Run);
registry->Register(OpenFileHandle);
registry->Register(Read);
registry->Register(ReadFileUtf8);
Expand Down
Original file line numberDiff line numberDiff line change
Expand Up@@ -67,7 +67,9 @@ async function checkAggregateError(op) {
tmpdir.refresh();
await checkAggregateError((filePath) => truncate(filePath));
await checkAggregateError((filePath) => readFile(filePath));
await checkAggregateError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkAggregateError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkAggregateError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-close-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -62,7 +62,9 @@ async function checkCloseError(op) {
tmpdir.refresh();
await checkCloseError((filePath) => truncate(filePath));
await checkCloseError((filePath) => readFile(filePath));
await checkCloseError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkCloseError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkCloseError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
4 changes: 3 additions & 1 deletion test/parallel/test-fs-promises-file-handle-op-errors.js
Original file line numberDiff line numberDiff line change
Expand Up@@ -56,7 +56,9 @@ async function checkOperationError(op) {
tmpdir.refresh();
await checkOperationError((filePath) => truncate(filePath));
await checkOperationError((filePath) => readFile(filePath));
await checkOperationError((filePath) => writeFile(filePath, '123'));
// More than one write chunk (512 KiB), so that writeFile(path) goes through
// a FileHandle as well.
await checkOperationError((filePath) => writeFile(filePath, '123'.repeat(200_000)));
if (common.isMacOS) {
await checkOperationError((filePath) => lchmod(filePath, 0o777));
}
Expand Down
Loading
Loading