how to execute es6 scripts from CLI - javascript

I have the latest NodeJS installed and for any JavaScript files, I can execute it with node myscript.js but recently I'm learning es6 and for some of the latest syntax, it just pop out some errors/exceptions while executing. I tried babel-cli, but didn't seem to work as it is for compile es6 to 5 not for command line execute.

1) To enable the support of ES6, use the --harmony flag:
node --harmony myscript.js
This will enable the available ES6 syntax in node. But notice it's currently a limited subset of the ES6 standard (see the compatibility table).
2) To have a complete compatibility, you have to use babel node.
Install #babel/node to get a babel-node executable which works exactly the same as Node.js's CLI, only it will compile ES6 code before running it.
babel-node myscript.js

For simple ES6 or even Typescript experimentation, maybe Deno could be considered nowadays. It supports newest ES (and TS) out of the box without needing any additional tooling.

#source1
https://dev.to/geekygeeky/get-started-with-es6-javascript-for-writing-nodejs-using-express-544h
#create dir /project1
mkdir /project1
cd /project1
#install babel etc
npm i #babel/cli #babel/core #babel/node #babel/preset-env --save-dev
npm i #babel/plugin-proposal-class-properties #babel/plugin-proposal-object-rest-spread --save-dev
npm i rimraf nodemon --save-dev
#initialize project1
#https://philna.sh/blog/2019/01/10/how-to-start-a-node-js-project/
npm init
#edit /project1/package.json
nano /project1/package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "rimraf dist && babel src --out-dir dist --copy-files",
"start": "node dist/app.js",
"start:dev": "nodemon --exec babel-node src/app.js"
},
#edit /project1/.babelrc
nano /project1/.babelrc
{ "presets": [
["#babel/env", {
"targets": {
"node": "current"
}
}]
],
"plugins": [
"#babel/plugin-proposal-class-properties",
"#babel/plugin-proposal-object-rest-spread"
]
}
#install express
npm i express --save
#open a bash shell
#create /project1/src
mkdir src
cd src
#edit /project1/src/app.js
nano /project1/src/app.js
import express, { json } from 'express';
import items from './items';
const app = express();
app.use(json())
const PORT = process.env.PORT || 3000;
app.get('/', async (req, res) => {
res.json({ status: true, message: "Our node.js app works" })
});
app.get('/items', (req, res) => {
res.json({ status: true, message: "Fetched all items", data: items })
})
app.listen(PORT, () => console.log(`App listening at port ${PORT}`));
#edit /project1/src/items.js
nano items.js
const items = [
{
id: 1,
username: "John doe",
cartItems: ['football', 'ps5', 'cd-rom'],
},
{
id: 2,
username: "Jane doe",
cartItems: ['mobile phone', 'game pad'],
}
];
export default items;
#open another bash shell
#run server
cd /project1
npm run start:dev
#keep the server running
#check your app via browser
http://localhost:3000
http://localhost:3000/items

Related

Reading enviromental variable problem in node.js

Here is my excel.js:
let test = async () => {
console.log(process.env.DATABASE_HOST);
.......
}
test();
Here is my package.json fragment:
"scripts": {
.............
"excel": "cross-env NODE_ENV=development node ./server/excel.js",
"test": "react-scripts test"
}
My .env.development is stored in the application root folder.
Here is my .env.development:
DATABASE_HOST=dbServer
When I execute the following command line in the application root folder:
npm run excel
It should return "dbServer", unfortunately, it returns undefined.
How can I fix it?
Install dotenv package, and require it require('dotenv').config()

dataSource flag in typeorm cli

I'm starting a project with typeorm. My configuration file looks like this:
ormconfig.js
import dotenv from 'dotenv'
dotenv.config();
const {
DATABASE_HOST,
DATABASE_PORT,
DATABASE_NAME,
DATABASE_PASSWORD
} = process.env
export default {
type: 'postgres',
host: DATABASE_HOST,
port: DATABASE_PORT,
database: DATABASE_NAME,
password: DATABASE_PASSWORD,
entities: [
"./api/modules/documents/entity/*.js",
],
migrations: [
"./api/database/migrations/*.js",
],
cli: {
migrationsDir: "./api/database/migrations",
entitiesDir: "api/database/modules/**/entity"
}
}
package.json scripts
"scripts": {
"gulp": "node_modules/gulp-cli/bin/gulp.js",
"start": "nodemon ./src/app.js",
"start:api": "nodemon ./api/server.js",
"typeorm": "node ./node_modules/typeorm/cli.js --config ./ormconfig.js"
},
When i try to run the command yarn typeorm migration:run its show this message:
Runs all pending migrations.
Opções:
-h, --help Exibe ajuda [booleano]
-d, --dataSource Path to the file where your DataSource instance is defined.
[obrigatório]
-t, --transaction Indicates if transaction should be used or not for
migration run. Enabled by default. [padrão: "default"]
-v, --version Exibe a versão [booleano]
Missing required argument: dataSource
What would be datasource flag?
I tried with typeorm cli installed globally, same problem happens
Looks like you are using typeorm 0.3.x in your project while you are following 0.2.x configurations. Check your installed version on your package.json.
If you are using 0.3.x and want to keep with the current version you should follow the documentation: https://typeorm.io/data-source
Otherwise you can just downgrade your version executing:
npm install typeorm#0.2.45

Electron.js/Parcel Error: fs.existsSync is not a function

I am using the Electron/Parcel boilerplate electron-react-parcel-boilerplate which works great out of the box.
However, when using the redux-beacon-electron package, I am getting the following error in the electron JS console:
Uncaught TypeError: fs.existsSync is not a function
at getElectronPath (index.js:7)
at Object.parcelRequire.node_modules/electron/index.js.fs (index.js:18)
at newRequire (src.a2b27638.js:47)
at localRequire (src.a2b27638.js:53)
at Object.parcelRequire.node_modules/electron-ga/lib/side-effects.js.electron (side-effects.ts:1)
at newRequire (src.a2b27638.js:47)
at localRequire (src.a2b27638.js:53)
at Object.parcelRequire.node_modules/electron-ga/lib/helpers.js.qs (helpers.ts:4)
at newRequire (src.a2b27638.js:47)
at localRequire (src.a2b27638.js:53)
and in the terminal where we run yarn start:
[0] ⚠️ /Users/nyxynyx/electron-app/node_modules/electron/index.js:8:41: Cannot statically evaluate fs argument
[0] 6 | function getElectronPath () {
[0] 7 | if (fs.existsSync(pathFile)) {
[0] > 8 | var executablePath = fs.readFileSync(pathFile, 'utf-8')
[0] | ^
[0] 9 | if (process.env.ELECTRON_OVERRIDE_DIST_PATH) {
[0] 10 | return path.join(process.env.ELECTRON_OVERRIDE_DIST_PATH, executablePath)
[0] 11 | }
My gut feeling is that Parcel was not properly targeting Electron when starting it using yarn start, so I tried changing
"react-start": "parcel -p 3000 index.html --out-dir build",
to
"react-start": "parcel -p 3000 index.html --out-dir build --target node",
and
"react-start": "parcel -p 3000 index.html --out-dir build --target electron",
but now the Electron app does not even launch on running yarn start, and nothing appears when trying to load http://localhost:3000 either after running yarn start or yarn react-start.
Why is it not working and is it possible to solve this error?
Thank you!
GitHub Repo
https://github.com/nyxynyx/electron-react-parcel-boilerplate-problem
Using
react-dom#16.13.1
react-redux#7.2.0
react#16.13.1
redux-beacon-electron#1.0.1
redux#4.0.5
electron#8.2.3
parcel-bundler#1.12.4
packages.json
{
"name": "electron-react-parcel",
"version": "1.0.0",
"description": "Electron app build using ReactJS and Parcel web application bundler",
"main": "src/electron.js",
"scripts": {
"react-start": "parcel -p 3000 index.html --out-dir build",
"react-build": "parcel build index.html --out-dir build --public-url ./",
"electron-build": "electron-builder -mwl",
"clean-build": "rm -rf build/ .cache dist/",
"build": "yarn clean-build && yarn react-build && yarn electron-build",
"start": "concurrently \"cross-env BROWSER=none yarn react-start\" \"wait-on http://localhost:3000 && electron . \"",
...
nodeIntegration: true
Tried setting to true as suggested by #tpikachu, but the same error persists...
electron.js (usually named main.js)
function createWindow() {
const { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
mainWindow = new BrowserWindow({
width: Math.round(width * 0.9),
height: Math.round(height * 0.9),
webPreferences: {
nodeIntegration: true,
}
});
mainWindow.loadURL(
isDev
? "http://localhost:3000"
: `file://${path.join(__dirname, "../build/index.html")}`
);
mainWindow.on("closed", () => (mainWindow = null));
}
app.on("ready", async () => {
createWindow();
...
});
Due to conflicts of package versions. Such as electron-ga#1.0.6 has electron#^1.8.2
Even we fix the package conflicts using electron-ga#1.0.6 won't be stable and not fit for the latest electron version.
We can use electron-google-analytics rather than electron-ga

Nodemon starts 2 instances of node when executed as a module in a javascript file

I am trying to execute a node application through nodemon. I have a index.js file as entry point of my application and a main.js file as:
var nodemon = require('nodemon');
/**
* some setup done
*/
nodemon({}).on('quit', ()=> {...});
with the config nodemon.json as:
{
"env": {
...
},
"execMap": {
"js": "node --inspect --max-old-space-size=4096"
},
"watch": [
"src/server",
"config",
"dist"
]
}
When i execute the main.js via npm script and run ps command in terminal, I am seeing 2 instances of my node application being run as:
12752 ttys001 0:02.53 /Users/testUser/.nvm/versions/node/v8.17.0/bin/node --inspect --max-old-space-size=4096 index.js
12777 ttys001 0:02.61 /Users/testUser/.nvm/versions/node/v8.17.0/bin/node --inspect --max-old-space-size=4096 --inspect-port=9230 /Users/testUser/projects/nodeProj/index.js
Also I am only able to attach node debugger on PORT 9230 not on 9229!
Why is such thing happening?

Travis CI NodeJs build runs locally but gets a permission denied on Travis CI

So when I run locally the mocha test inside my repo It works just fine but when I push a commit and it runs on travis CI I keep getting this error:
sh: 1: mocha: Permission denied
npm ERR! Test failed. See above for more details.
my .travis.yml
language: node_js
node_js:
- "6"
install:
-npm install
before_script: npm install -g mocha
before_script: chmod 0777 ./node_modules/.bin/mocha
package.json
{
"name": "skeletonapp",
"version": "0.0.0",
"description": "skeletonapp",
"main": "index.js",
"author": {
"name": "li"
},
"scripts": {
"test": "mocha"
},
"dependencies": {
"chai": "^3.5.0",
"mocha": "^3.1.2"
}
}
structure of files
https://travis-ci.org/LiamDotPro/Travis-CI-NodeJS-Skeleton---Mocha-Chai/builds/173340318
test.js
var assert = require('assert');
describe('Array', function () {
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(-1, [1, 2, 3].indexOf(4));
});
});
});
Turn on the execute permission on node_modules/.bin: https://github.com/travis-ci/travis-ci/issues/6828#issuecomment-258581083
Or, remove node_modules from your Git repository, and let Travis install it with npm install. (See https://docs.travis-ci.com/user/languages/javascript-with-nodejs#Travis-CI-uses-npm.)
Do not install mocha to Travis-CI manually. It's here by default.
Just remove your before_script's statements from the .travis.yml file.

Categories