0

I am attempting to implement the lowdb NPM package for use with node.js, but I am running into permissions errors. I have tried all of the examples listed in the readme located at https://github.com/typicode/lowdb/tree/master/examples, but all are returning the same error.

For ease, here is the specific code I tried running from the node CLI:

const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')

const adapter = new FileSync('db.json')
const db = low(adapter)

db.defaults({ posts: [] })
  .write()

const result = db.get('posts')
  .push({ name: process.argv[2] })
  .write()

console.log(result)

I am executing with this command:

$ node cli.js hello

This should be the result:

# [ { title: 'hello' } ]

Instead I receive this error:

[server]$ node cli.js hello
fs.js:549
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: EACCES: permission denied, open 'db.json'
    at Error (native)
    at Object.fs.openSync (fs.js:549:18)
    at fs.writeFileSync (fs.js:1156:15)
    at FileSync.read (/home/nodeadmin/datadir/estimup/node_modules/lowdb/adapters/FileSync.js:46:9)
    at LodashWrapper.db.read (/home/nodeadmin/datadir/estimup/node_modules/lowdb/lib/main.js:32:21)
    at module.exports (/home/nodeadmin/datadir/estimup/node_modules/lowdb/lib/main.js:51:13)
    at Object.<anonymous> (/home/nodeadmin/datadir/estimup/cli.js:5:12)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)

I have attempted creating the db.json file manually in advance and gave it chmod 644 permissions, still to no avail.

Dshiz
  • 3,099
  • 3
  • 26
  • 53

1 Answers1

0

I found a working solution that, while not perfect, I will share to help those who may just need it working for development reasons.

The underlying issue is that node needs the rights to create/modify files. An easy way to make this work is simply: $ sudo node cli.js

I wanted nodemon to run cli.js however. The problem there was that I was receiving a command not found error when attempting $ sudo nodemon cli.js. This is because of a separate problem with my nodemon installation that I have yet to figure out.

The workaround that worked for me here was found in an answer to this stack: nodemon not found in npm

Specifically, add the following to package.json:

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon cli.js"
}

Then $ sudo npm start

Now nodemon is running my application with elevated privileges and I can move on with my project.

Dshiz
  • 3,099
  • 3
  • 26
  • 53