Creating directory on root doesn't work via npm but does running node directly

Viewed 50

app.js (root is not file owner)

var fs = require('fs');
fs.mkdirSync('/root/tmp');

package.json

{
  "scripts": {
    "app": "node app.js"
  }
}

When I run as root npm run app I got

> app
> node app.js

node:internal/fs/utils:344
    throw err;
    ^

Error: EACCES: permission denied, mkdir '/root/tmp'

But it works when I run just node app.js. Which setting/option of npm can help me run npm run app without errors?

Why npm run change user? How to force npm not to change user?

1 Answers

I can replicate the behavior you see on Linux if I run the commands in a shell I've run via sudo, like this: sudo bash. As in the question, npm run app fails but node app.js works.

The difference is that npm run app runs the executable JavaScript file npm-cli.js from the npm package, which looks like this:

#!/usr/bin/env node
require('../lib/cli.js')(process)

That tells us it's running node via env.

So I got to thinking: What user does that run as? So I added "who": "whoami" to package.json and did npm run who. The answer is: It runs as my normal account, not as root, even when I run that from a shell I've launched via sudo bash. My normal user account can't (of course) create subdirectories of root.

Related