fs: throw errors from fs.ftruncateSync in JS

PR-URL: https://github.com/nodejs/node/pull/18348
Refs: https://github.com/nodejs/node/issues/18106
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
This commit is contained in:
Joyee Cheung 2018-01-24 09:20:30 +08:00
parent 5583981c52
commit b3a7df7c6d
No known key found for this signature in database
GPG Key ID: F586868AAD831D0C
3 changed files with 45 additions and 8 deletions

View File

@ -995,7 +995,11 @@ fs.ftruncateSync = function(fd, len = 0) {
validateUint32(fd, 'fd');
validateLen(len);
len = Math.max(0, len);
return binding.ftruncate(fd, len);
const ctx = {};
binding.ftruncate(fd, len, undefined, ctx);
if (ctx.errno !== undefined) {
throw new errors.uvException(ctx);
}
};
fs.rmdir = function(path, callback) {

View File

@ -711,18 +711,24 @@ static void Rename(const FunctionCallbackInfo<Value>& args) {
static void FTruncate(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
const int argc = args.Length();
CHECK_GE(argc, 3);
CHECK(args[0]->IsInt32());
const int fd = args[0].As<Int32>()->Value();
CHECK(args[1]->IsNumber());
const int64_t len = args[1].As<Integer>()->Value();
int fd = args[0]->Int32Value();
const int64_t len = args[1]->IntegerValue();
if (args[2]->IsObject()) {
CHECK_EQ(args.Length(), 3);
if (args[2]->IsObject()) { // ftruncate(fd, len, req)
CHECK_EQ(argc, 3);
AsyncCall(env, args, "ftruncate", UTF8, AfterNoArgs,
uv_fs_ftruncate, fd, len);
} else {
SYNC_CALL(ftruncate, 0, fd, len)
} else { // ftruncate(fd, len, undefined, ctx)
CHECK_EQ(argc, 4);
fs_req_wrap req_wrap;
SyncCall(env, args[3], &req_wrap, "ftruncate",
uv_fs_ftruncate, fd, len);
}
}

View File

@ -455,3 +455,30 @@ function re(literals, ...values) {
validateError
);
}
// ftruncate
{
const validateError = (err) => {
assert.strictEqual(err.syscall, 'ftruncate');
// Could be EBADF or EINVAL, depending on the platform
if (err.code === 'EBADF') {
assert.strictEqual(err.message, 'EBADF: bad file descriptor, ftruncate');
assert.strictEqual(err.errno, uv.UV_EBADF);
} else {
assert.strictEqual(err.message, 'EINVAL: invalid argument, ftruncate');
assert.strictEqual(err.errno, uv.UV_EINVAL);
assert.strictEqual(err.code, 'EINVAL');
}
return true;
};
const fd = fs.openSync(existingFile, 'r');
fs.closeSync(fd);
fs.ftruncate(fd, 4, common.mustCall(validateError));
assert.throws(
() => fs.ftruncateSync(fd, 4),
validateError
);
}