Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix node.js on macOS write to file permission denied error?

Tags:

node.js

macos

I set up node.js to write to file on its local folder as such:

Note: I have already use sudo chmod 755 req.txt and sudo chmod 755 bodyhead.txt to set the permission of the file to be writable.

fs.writeFile('/req.txt', req + '\r\n!ended!\r\n', function(err) {
  if(err) {
    return console.log(err);
  }
});
fs.writeFile('/bodyhead.txt', bodyhead + '\r\n!ended!\r\n', function(err) {
  if(err) {
    return console.log(err);
  }
});

And received:

{ Error: EACCES: permission denied, open '/req.txt' errno: -13, code: 'EACCES', syscall: 'open', path: '/req.txt' }

as well as

{ Error: EACCES: permission denied, open '/bodyhead.txt' errno: -13, code: 'EACCES', syscall: 'open', path: '/bodyhead.txt' }

like image 336
Aero Wang Avatar asked Jul 28 '17 06:07

Aero Wang


People also ask

How do I resolve permission denied error?

For solving this error, you need to add the correct permissions to the file to execute. However, you need to be a “root” user or have sudo access for changing the permission. For changing the permission, Linux offers a chmod command. The chmod stands for change mod.

How do I change permissions in node JS?

The fs. chmod() method is used to change the permissions of a given path.

What might be causing the error error Eacces Permission denied access '/ usr local lib Node_modules '?

This means you do not have permission to write to the directories npm uses to store global packages and commands. Try running commands: sudo chmod u+x -R 775 ~/. npm and sudo chown $USER -R ~/. npm or you can just run any npm command with sudo , that should get resolve your issue.


1 Answers

I set up node.js to write to file on its local folder...

But you're not writing to the local folder, you're writing to the root of your filesystem:

fs.writeFile('/req.txt', ...
              ^ root of filesystem

Instead, remove the leading slashes from the filenames you're trying to write:

fs.writeFile('req.txt', ...
fs.writeFile('bodyhead.txt', ...
like image 72
robertklep Avatar answered Oct 02 '22 00:10

robertklep