Skip to content

fs.writeFileSync in Node 20 failed to write file in TMPDIR #52079

Closed
@fannheyward

Description

@fannheyward

Version

v20.11.1

Platform

macOS arm64

Subsystem

No response

What steps will reproduce the bug?

fs.writeFileSync failed to EACCES: permission denied error with Node 20, but works with Node 18.

import fs from 'fs'
import path from 'path'
import os from 'os'

function modify(fsPath, key, value) {
  let dir = path.dirname(fsPath)
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true })
  let content = fs.readFileSync(fsPath, { encoding: 'utf8', flag: 'a+' })
  content = content || '{}'
  content = JSON.parse(content)
  content[key] = value
  content = JSON.stringify(content)
  fs.writeFileSync(fsPath, content)
}

const p = path.join(os.tmpdir(), 'test', 'foo.json')
modify(p, 'key', 'foobar')

How often does it reproduce? Is there a required condition?

No response

What is the expected behavior? Why is that the expected behavior?

No response

What do you see instead?

❯ /opt/homebrew/opt/node@20/bin/node x.mjs
node:fs:2352
    return binding.writeFileUtf8(
                   ^

Error: EACCES: permission denied, open '/private/var/folders/7q/r_8_1r5d5bb0dfycljk5pr1h0000gn/T/test/foo.json'
    at Object.writeFileSync (node:fs:2352:20)
    at modify (file:///Users/fannheyward/x.mjs:13:6)
    at file:///Users/fannheyward/x.mjs:17:1
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at async ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at async loadESM (node:internal/process/esm_loader:28:7)
    at async handleMainPromise (node:internal/modules/run_main:113:12) {
  errno: -13,
  code: 'EACCES',
  syscall: 'open',
  path: '/private/var/folders/7q/r_8_1r5d5bb0dfycljk5pr1h0000gn/T/test/foo.json'
}

Node.js v20.11.1

❯ ls -lh /private/var/folders/7q/r_8_1r5d5bb0dfycljk5pr1h0000gn/T/test/foo.json
----------  1 fannheyward  staff     0B  3 14 12:38 /private/var/folders/7q/r_8_1r5d5bb0dfycljk5pr1h0000gn/T/test/foo.json

Works with Node 18:

~ 
❯ /opt/homebrew/opt/node@18/bin/node x.mjs

❯ ls -lh /private/var/folders/7q/r_8_1r5d5bb0dfycljk5pr1h0000gn/T/test/foo.json
-rw-r--r--@ 1 fannheyward  staff    16B  3 14 12:36 /private/var/folders/7q/r_8_1r5d5bb0dfycljk5pr1h0000gn/T/test/foo.json

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    fsIssues and PRs related to the fs subsystem / file system.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions