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.
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.
Related
When I am running nodemon run start it is giving me the following error
I am running this on macos. Not sure if that matters or not.
ERROR
node:internal/modules/cjs/loader:926
throw err;
^
Error: Cannot find module '/Users/jarvis/Documents/Backend/mongoTelusko/run'
at Function.Module._resolveFilename (node:internal/modules/cjs/loader:923:15)
at Function.Module._load (node:internal/modules/cjs/loader:768:27)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
[nodemon] app crashed - waiting for file changes before starting...
This is my app.js file
const express = require('express')
const mongoose = require('mongoose')
const url = 'mongodb://localhost/AlienDBex'
enter code here
const app = express()
mongoose.connect(url, {useNewUrlParser: true})
const con = mongoose.connection
con.on('open', function(){
console.log('Connected...')
})
This is my package.json file
{
"name": "mongotelusko",
"version": "1.0.0",
"main": "app.js",
"scripts": {
"start": "nodemon app.js"
},
"author": "malay",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"mongodb": "^3.6.5",
"mongoose": "^5.12.2"
},
"devDependencies": {
"nodemon": "^2.0.7"
},
"description": ""
}
"scripts": {
"start": "nodemon app.js"
},
Since you have specified "start" script in package.json, npm start command automatically calls nodemon app.js
However, you can also run the nodemon app.js manually which also has the same effect.
Wrong: nodemon run start
Correct: nodemon app.js or npm start
You're running nodemon run start, which tells nodemon to execute run (run.js) with argument start. Did you mean to use npm run start? Hint: You can also use npm start as a shortcut.
I've got the same error while I'm trying to run the code on my Mac.
I found why it is showing me this error:
first reason is that I've installed Node.js through an installation pack downloaded from [nodejs.org][1], but I should've installed node from the Terminal.
second reason is that I found out that I was trying to run the file from a different folder. I was in folder /users/practice/file-manager/frontend - trying to run the code from file which is located in directory /users/practice/file-manager/backend - the main reason which caused this error.
As a solution that worked for me:
make sure you've installed Node.js from terminal
make sure you're in the right directory when you're trying to run the .js file.
Maybe this information helps you.
My solution after trying new files, etc... didnt work. Then starting from the beginning:
deleting node.js and clearing cache about npm (from appdata)
creating new file and being sure about path you can confirm with 'cd'
trying to re-install npm_modules at my project folder.(npm install)
Then it worked.
I'm currently in the process of containerizing my App. Part of the App is a NodeJS Express Backend.
It works without any issues when I run it on my console with node index.js or nodemon index.js.
Inside the middlewares/index.js I do import authJwt.js and verifySignup.js via require('./verifySignup) and require('./authJwt).
This works unsurprisingly well when I run my app from the console. However If i build my docker-image using the following Dockerfile-Code:
# build environment
FROM node:14
# Working Directoy
WORKDIR /app
ENV FILE_UPLOADS="./files/uploads"
ENV FILE_UPLOADS_PART="./files/uploads_part"
ENV PORT=3001
ENV DB_HOST="localhost"
ENV DB_USER="root"
ENV DB_PASSDWORD="root_password"
ENV DB_NAME="upload_db"
ENV SECRET_KEY="bezkoder-secret-key"
# Copy Needed Files for Dependencies
COPY package.json /app/package.json
COPY yarn.lock /app/yarn.lock
# Install with YARN
RUN yarn install
# Copy Source Files
COPY ./ /app
EXPOSE 3001
CMD [ "yarn", "start" ]
When I run the Image it immediately terminates. Looking at the logs I find the following error:
$ docker logs 031241ce227a
yarn run v1.22.5
$ node index.js
internal/modules/cjs/loader.js:895
throw err;
^
Error: Cannot find module './verifySignUp'
Require stack:
- /app/middleware/middleware.js
- /app/routes/auth.routes.js
- /app/index.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:892:15)
at Function.Module._load (internal/modules/cjs/loader.js:742:27)
at Module.require (internal/modules/cjs/loader.js:964:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (/app/middleware/middleware.js:2:22)
at Module._compile (internal/modules/cjs/loader.js:1075:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1096:10)
at Module.load (internal/modules/cjs/loader.js:940:32)
at Function.Module._load (internal/modules/cjs/loader.js:781:14)
at Module.require (internal/modules/cjs/loader.js:964:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'/app/middleware/middleware.js',
'/app/routes/auth.routes.js',
'/app/index.js'
]
}
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I then exported my docker-image using docker export adoring_kowalevski > contents.tar to look at the filesystem inside the image, but everything is where it should be.
In a desperate attempt I hoped, that the issue might occur because I have multiple index.js in different folders, so I changed the names of all except the one in the root directory, but issue persisted. This is why in the error-log there is a middleware/middleware.js, it was after renaming the middleware/index.js.
Edit:
I tried using rfr to change my references from require('../middleware') to rfr('middleware'). It still workds from console but still not inside the container. So it seems that the issue doesn't occur because of the relative file paths.
Turns out I'm stupid (somewhat).
The import inside middleware/index.js looked like this require('./verifySignUp').
If we look at the file verifySignup.js inside the middleware Folder we can see, that it is named without the capital 'U'.
Why did it still work from console?
Inside verifySignup.js is the following piece of code:
module.exports = {
authJwt,
verifySignUp
};
Here it is written with capital 'U'. This means that running node index.js from the console only cared about whatever was written in the module.exports and not the actual Filename, however when running inside Docker, the Filename matters.
Renaming the file from verifySignup.js to verifySignUp.js solved my problems.
I'm trying to get a simple electron application running that interacts with an HID device.
I am running into a lot of difficulty, I am able to install and run node-hid, just not within electron.
My package.json looks like this:
{
"name": "test-proj",
"version": "1.0.0",
"description": "",
"main": "main.js",
"scripts": {
"start": "electron .",
"rebuild": "electron-rebuild --force",
"postinstall": "electron-rebuild"
},
"author": "me",
"license": "ISC",
"devDependencies": {
"electron": "^9.2.0",
"electron-rebuild": "^1.11.0"
},
"dependencies": {
"node-hid": "^1.3.0"
}
}
My main.js has the standard electron demo boilerplate code plus some HID calls:
const {app, BrowserWindow, ipcMain} = require('electron');
var HID = require('node-hid');
var device = new HID.HID(5824, 1500);
// Standard electron app window stuff
When trying to run the app I immediately get an error on new HID.HID():
Error: Module did not self-register: '\\?\C:\Users\Nathan\Desktop\carriage_return_app\node_modules\node-hid\build\Release\HID.node'.
at process.func [as dlopen] (electron/js2c/asar.js:140:31)
at Object.Module._extensions..node (internal/modules/cjs/loader.js:1034:18)
at Object.func [as .node] (electron/js2c/asar.js:140:31)
at Module.load (internal/modules/cjs/loader.js:815:32)
at Module._load (internal/modules/cjs/loader.js:727:14)
at Function.Module._load (electron/js2c/asar.js:769:28)
at Module.require (internal/modules/cjs/loader.js:852:19)
at require (internal/modules/cjs/helpers.js:74:18)
at bindings (C:\Users\Nathan\Desktop\carriage_return_app\node_modules\bindings\bindings.js:112:48)
at loadBinding (C:\Users\Nathan\Desktop\carriage_return_app\node_modules\node-hid\nodehid.js:25:42)
Looking around I have seen a few examples of how to install node-hid and use it in electron, but none have helped me.
I have followed the electron-rebuild instructions here: https://www.electronjs.org/docs/tutorial/using-native-node-modules
I have also followed the instructions and copied the examples from here: https://github.com/node-hid/node-hid#electron-projects-using-node-hid
No luck. I get module did not self-register every time. node-hid is supposed to support electron and I don't see other people complaining.
Anyone come across this or have ideas to fix the issue?
The problem has been solved, so I will mark this as answered. I think I would still like more information on WHY though.
The hint came from building the two example projects:
https://github.com/todbot/electron-hid-toy
https://github.com/todbot/electron-hid-test
Running the first item, electron-hid-test worked off the bat. Adding electron-builder as a dependency and adding "postinstall": "electron-builder install-app-deps" as a script solved the issue in my project, I don't want electron-builder yet but at least it indicated that node-hid can work with electron given a specific setup.
The second item also worked, but not with:
npm install
npm rebuild
npm start
Instead it was specifically required to add the run command to the rebuild command:
npm install
npm run rebuild
npm start
After that, it works.
Any insights as to why this behaves differently?
I am trying this article working on a react calculator
I set my package.json with "start": "babel-node ./server/server.js" in the scripts. When I run npm start, errors shows up. yarn start gives more details error message shown there.
max#DESKTOP-4J1U771 MINGW64 ~/Documents/react-calculator (master) $
yarn start yarn run v1.7.0 warning package.json: No license field $
babel-node ./server/server.js
C:\Users\max\Documents\react-calculator\node_modules\babel-core\lib\transformation\file\logger.js:41
throw new Constructor(this._buildMessage(msg));
^
ReferenceError: [BABEL]
C:\Users\max\Documents\react-calculator\server\server.js: Unknown
option: base.0. Check out h ttp://babeljs.io/docs/usage/options/ for
more information about options.
A common cause of this error is the presence of a configuration
options object without the corresponding preset name. Example:
Invalid: { presets: [{option: value}] } Valid: { presets:
[['presetName', {option: value}]] }
For more detailed information on preset configuration, please see
https://babeljs.io/docs/en/plugins#pluginpresets-op tions.
at Logger.error (C:\Users\max\Documents\react-calculator\node_modules\babel-core\lib\transformation\file\logger.j
s:41:11)
at OptionManager.mergeOptions (C:\Users\max\Documents\react-calculator\node_modules\babel-core\lib\transformation
\file\options\option-manager.js:226:20)
at OptionManager.init (C:\Users\max\Documents\react-calculator\node_modules\babel-core\lib\transformation\file\op
tions\option-manager.js:368:12)
at File.initOptions (C:\Users\max\Documents\react-calculator\node_modules\babel-core\lib\transformation\file\inde
x.js:212:65)
at new File (C:\Users\max\Documents\react-calculator\node_modules\babel-core\lib\transformation\file\index.js:135
:24)
at Pipeline.transform (C:\Users\max\Documents\react-calculator\node_modules\babel-core\lib\transformation\pipelin
e.js:46:16)
at Object.transformFileSync (C:\Users\max\Documents\react-calculator\node_modules\babel-core\lib\api\node.js:152:
10)
at compile (C:\Users\max\Documents\react-calculator\node_modules\babel-register\lib\node.js:118:20)
at loader (C:\Users\max\Documents\react-calculator\node_modules\babel-register\lib\node.js:144:14)
at Object.require.extensions.(anonymous function) [as .js] (C:\Users\max\Documents\react-calculator\node_modules\
babel-register\lib\node.js:154:7) error Command failed with exit code
1. info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this > command.
Does anyone see what's going on here and how to solve it?
Use create-react-app. It is way simpler than configuring babel and creating React projects the old way. To use it, go to the directory you want your project to be in, and type in your terminal: create-react-app [project-name]. This will do all the configuring for you and make it easier for you. The installation and configuration of React mentioned in the article is outdated, but you can still follow everything else in that tutorial. Good luck!
I have a simple node server:
//server.js
import express from 'express';
import React from 'react';
...
When I try to run this using Forever:
forever start -c "babel-node --experimental" server.js
, it errors out due to use of import
/Applications/MAMP/htdocs/React/ReactBoilerplates/koba04/app/server.js:1
(function (exports, require, module, __filename, __dirname) { import express
^^^^^^
SyntaxError: Unexpected reserved word
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:902:3
error: Forever detected script exited with code: 8
I have also tried pm2 and nodemon, I get same error there as well.
For pm2, I followed this issue https://github.com/Unitech/PM2/issues/1167, but it didn't work either. What am I doing wrong here?
forever start -c "node -r babel-register" ./src/index.js
Also works.
This works for on-the-fly transpilation for me: forever start -c node_modules/.bin/babel-node server.js
Another solution is using the Require Hook like this:
// server-wrapper.js
require('babel/register');
require('./server.js');
Then run forever start server-wrapper.js.
I suggest to precompile your es6 scripts into es5 scripts and run the app with a forever start server.js command where server.js is a result of precompilation.
If you're using react.js for an isomorphic app you also will be needed to precompile your scripts for browsers either (via browserify, webpack and so on).
So I see no profit to work with es6 scripts via on demand compilation versus precompilation with gulp or any other js building system.
In your package.json file under scripts tag add entry like below
in package.json under scripts tag
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "forever start -c babel-node src/index.js",
},
all the dependencies must include in dependencies tag in package.json file
then do a npm install then
run the server by executing npm start