Forever errors with babel-node - node.js

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

Related

DotEnv comments are crashing

I'm using dotenv version 16.0.0 in my NodeJS project but the comment feature that was recently added causes a crash. Without the comments the .env file works perfectly, loading values from it.
The .env file content:
# Print out information during runtime, useful for debugging problems not caught.
(true/false)
VERBOSE=false
# Database settings, update for actual deployment environment
DB_USERNAME=postgres
DB_PASSWORD=TINY_DUCK
DB_NAME=user_database
DB_HOST=localhost
DB_PORT=5432
The command to run the NodeJS project is:
mocha -r .env ./tests/testManager.js --exit
And the error message I get when running the NodeJS project:
× ERROR: C:\Users\thega\Source\Repos\network\.env:1
# Print out information during runtime, useful for debugging problems not caught. (true/false)
^
SyntaxError: Invalid or unexpected token
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at exports.requireOrImport (C:\Users\thega\source\repos\network\node_modules\mocha\lib\nodejs\esm-utils.js:60:20)
at async exports.handleRequires (C:\Users\thega\source\repos\network\node_modules\mocha\lib\cli\run-helpers.js:94:28)
at async C:\Users\thega\source\repos\network\node_modules\mocha\lib\cli\run.js:353:25
It looks to me as if you are trying to import the .env file as JS module instead of loading it with the dotenv package.
The -r flag to mocha means "require":
This will require a module before loading the user interface or test files.
It is useful for:
Test harnesses
Assertion libraries that has augment built-ins or global scope (such as should.js)
Instant ECMAScript modules using esm
Compilers like Babel via #babel/register or TypeScript using ts-node (using --require ts-node/register).
So it will try to load the file as JavaScript and of course that can't work.
Instead, you can require dotenv/config so it will parse the file for you and update process.env accordingly:
mocha -r dotenv/config ./tests/testManager.js --exit
Or, if you already do require('dotenv').config() in your code, you don't need any -r switch here at all.

How to install node-hid for electron

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?

NodeJs Npm Start works but node index.js doesn't. SyntaxError: Unexpected identifier

I have an app in NodeJS with Apollo Server, Graphql, etc. I want to use PM2 to have my index like a service so, when I close the console It dont stop.
When I execute npm start the server starts perfect. This is my start in package.json
"start": "nodemon ./index.js --exec babel-node -e js",
If I execute node index.js then this error appears.
/home/ubuntu/react/desafio/servidor/index.js:1
import express from 'express';
^^^^^^^
SyntaxError: Unexpected identifier
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:829:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
this is my index.js code
import express from 'express';
import { ApolloServer, AuthenticationError } from 'apollo-server-express';
import { typeDefs } from './data/schema';
import { resolvers } from './data/resolvers';
import jwt from 'jsonwebtoken';
import dotenv from 'dotenv';
import db from "./models";
dotenv.config({path:'variables.env'});
const cors = require('cors');
const app = express();
// enable cors
// app.use(cors());
const addToken = async (req) =>{
}
const server= new ApolloServer({
typeDefs,
resolvers
});
server.applyMiddleware({app});
app.listen({port:9000},()=> console.log(`Server Corriendo http://localhost:9000${server.graphqlPath}`));
what Im doing wrong?
node index.js will throw an error because your code is in ES6, to successfully run your code you will have to run it with babel-node which will compile it to ES5. babel-node comes with the babel-cli which you have to install.
" ./index.js --exec babel-node -e js" exactly does this which is to compile ES6 to ES5
Babel helps to turn our codes from ES6 to ES5. There are some ES6
features that our browsers and node are yet to understand, and older
browsers do not understand ES6 codes, so we use babel to compile our
code to ES5 so that both old browsers and new browsers can understand.
While import is indeed part of ES6, it is unfortunately not yet supported in NodeJS by default, and has only very recently landed support in browsers.
check this node import vs require
in node 9 ** it is enabled behind a flag, and uses the .mjs extension**
node --experimental-modules my-app.mjs
you can use require statements:
const express = require("express");
If you really want to use new ES6/7 features in NodeJS, you can compile it using Babel

Lowdb on Node.js failing with permissions error

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.

How can I run background task in node.js

I saw that I could run background tasks by using nohup node index.js.
My problem is related with following source.
https://github.com/Palpasa/Node-Express-Seed.
In this source, package.json file contains nodemon and it is working when I start the server with npm start.
For now, I tried to run the server in background.
But it is crashing with following error.
[nodemon] 1.14.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node app.js`
/home/tom/Documents/work/wallet/app/app.js:3
import bodyParser from 'body-parser';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
[nodemon] app crashed - waiting for file changes before starting...
How can I run this server in background?
You can run several screens on your putty.
screen
Then you will have one screen.
You can now run your node instance on this screen.
This screen is alive all the time.
Type CTRL+A+D to go out of the screen.
Your node instance is now always alive even you quit putty.
Child Process is what you would want to use.
const { spawn } = require('child_process');
const otherScript = spawn('node', ['script-you-wanna-run.js']);
otherScript.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
You probably need to use ES-2015 babel preset to transpile the import statements. If you don't need the ES6 import specifically, just use require
var bodyParser = require("body-parser")
On another note you can try using Forever npm package. This let's you start the node server in the background
FOREVER
npm install -g forever
forever start server.js
// To run on a custom po
PORT=3000 forever start server.js
You cannot run nodemon in the background (i.e nohup npm start <=> nohup nodemon app.js), nodemon supposed to be used for development environment, it let you see what changes are made on files during development, if you are looking for running express app in production, Then you should use a process manager, it restarts the app automatically when it crashes, or when changes are made, read this article for more information. Here is an example using pm2 module:
Install pm2:
npm install pm2 -g
Run app:
pm2 start app.js

Resources