unexpected token error with NPM? [duplicate] - node.js

I was experimenting on using Node version 6.2.1 with some of my code. Had plans to migrate most of the hyper-callback oriented codes to something that looks cleaner and maybe performs better.
I have no clue why, the terminal throws up an error when I try to execute the node code.
helloz.js
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ node helloz.js
/Users/bozzmob/Documents/work/nextgennms/rest/helloz.js:1
(function (exports, require, module, __filename, __dirname) { (async function testingAsyncAwait() {
^^^^^^^^
SyntaxError: Unexpected token function
at Object.exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:513:28)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Function.Module.runMain (module.js:575:10)
at startup (node.js:160:18)
at node.js:456:3
BOZZMOB-M-T0HZ:rest bozzmob$ node -v
v6.2.1
What am I missing? Please throw me some light on the same.
Update 1:
I tried to use Babel as Quentin suggested, But, I am getting the following error still.
Updated Code-
require("babel-core/register");
require("babel-polyfill");
(async function testingAsyncAwait() {
await console.log("Print me!");
})();
Logs-
BOZZMOB-M-T0HZ:rest bozzmob$ babel helloz.js > helloz.trans.js
SyntaxError: helloz.js: Unexpected token (3:7)
1 | require("babel-polyfill");
2 |
> 3 | (async function testingAsyncAwait() {
| ^
4 | await console.log("Print me!");
5 | })();

Async functions are not supported by Node versions older than version 7.6.
You'll need to transpile your code (e.g. using Babel) to a version of JS that Node understands if you are using an older version.
That said, versions of Node.js which don’t support async functions are now all past End Of Life and are unsupported, so if you are using an earlier version you should very strongly consider upgrading.

Nodejs supports async/await from version 7.6.
Release post: https://v8project.blogspot.com.br/2016/10/v8-release-55.html

Node.JS does not fully support ES6 currently, so you can either use asyncawait module or transpile it using Babel.
install
npm install --save asyncawait
helloz.js
var async = require('asyncawait/async');
var await = require('asyncawait/await');
(async (function testingAsyncAwait() {
await (console.log("Print me!"));
}))();

If you are just experimenting you can use babel-node command line tool to try out the new JavaScript features
Install babel-cli into your project
$ npm install --save-dev babel-cli
Install the presets
$ npm install --save-dev babel-preset-es2015 babel-preset-es2017
Setup your babel presets
Create .babelrc in the project root folder with the following contents:
{ "presets": ["es2015","es2017"] }
Run your script with babel-node
$ babel-node helloz.js
This is only for development and testing but that seems to be what you are doing. In the end you'll want to set up webpack (or something similar) to transpile all your code for production
babel-node sample code : https://github.com/stujo/javascript-async-await/tree/15abac
If you want to run the code somewhere else, webpack can help and here is the simplest configuration I could work out:
Full webpack example : https://github.com/stujo/javascript-async-await

node v6.6.0
If you just use in development. You can do this:
npm i babel-cli babel-plugin-transform-async-to-generator babel-polyfill --save-dev
the package.json would be like this:
"devDependencies": {
"babel-cli": "^6.18.0",
"babel-plugin-transform-async-to-generator": "^6.16.0",
"babel-polyfill": "^6.20.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator"]
}
and then, run your async/await script like this:
./node_modules/.bin/babel-node script.js

Though I'm coming in late, what worked for me was to install transform-async-generator and transform-runtime plugin like so:
npm i babel-plugin-transform-async-to-generator babel-plugin-transform-runtime --save-dev
the package.json would be like this:
"devDependencies": {
"babel-plugin-transform-async-to-generator": "6.24.1",
"babel-plugin-transform-runtime": "6.23.0"
}
create .babelrc file and write this:
{
"plugins": ["transform-async-to-generator",
["transform-runtime", {
"polyfill": false,
"regenerator": true
}]
]
}
and then happy coding with async/await

include and specify the node engine version to the latest, say at this time I did add version 8.
{
"name": "functions",
"dependencies": {
"firebase-admin": "~7.3.0",
"firebase-functions": "^2.2.1",
},
"engines": {
"node": "8"
},
"private": true
}
in the following file
package.json

Related

babel-node doesn't transpile JSX in npm react script for Node version 14

I'm having a big problem with running my npm script using babel-node. This script generates static error pages from react components. With Node versions 10 and 12 it is running successfully, but when I have updated my node version to 14 babel-node seems to stop transpiling JSX. Now I get this error:
<MuiThemeProvider theme={theme}>
^
SyntaxError: Unexpected token '<'
at Loader.moduleStrategy (internal/modules/esm/translators.js:140:18)
at async link (internal/modules/esm/module_job.js:42:21)
My devDependencies in package.json file:
"devDependencies": {
"#babel/node": "^7.14.2",
"#babel/preset-env": "^7.14.2",
"babel-plugin-styled-components": "^1.12.0",
"prettier": "2.3.0"
}
and script in package.json:
"generate-error-pages": "babel-node scripts/generate-error-pages.js"
And this is my .babelrc file:
{
"presets": ["#babel/preset-env", "#babel/react"],
"plugins": [["styled-components", { "ssr": true }]]
}
I can't make it work with Node version 14 like it worked with version 10 and 12.
Creating new repository helped me find the problem. In previous versions of Node I had to add
"type": "module"
in package.json because without it there was an exception caused by using import in JS script. Now I observed that in Node 14 I don't need "type": "module" anymore. This was even the problem of described exception. After deleting this from package.json it is now working also in Node 14.

node index.js returning "Unexpected token >"

I have been doing javascript for a while and decided to start node.js. I am running node.js and express on a raspberry pi (but I doubt this is the root of the problem). I am making a chat app with socket.io, and the instructions said to create a package.json:
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {}
}
Then I ran the command npm install express#4.
After that, I made an index.js file.
This is the code.
const app = require('express')();
const http = require('http').createServer(app);
app.get('/', (req, res) => {
res.send('<h1>Hello world</h1>');
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
Error code:
/home/pi/Desktop/index.js:4
app.get('/', (req, res) => {
SyntaxEror: Unexpected token >
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:906:3
Thanks!
Arrow functions are an ES2015 feature. Generally, environments after 2015 support arrow functions (and other modern syntax). Node 0.10.29 was released in 2014.
To fix it, install the latest long-term version that your machine supports: probably 14.6.0. See here.
Uninstall Node with
sudo apt remove nodejs
and then install it (which will fetch the latest version)
sudo apt install nodejs
As I remember this can be the reason. Just add the "script" property like this:
"scripts": {
"start": "node index.js"
}
Also there's not express installed. If this will not work, please show the complete view of package.json

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?

async / await breaks my Webpack build for AWS Lambda; how can I migrate to Node 8.10?

Note: this is a Q&A on migrating AWS Lambda Webpack builds from v6.10 to v8.10 — no help is needed, but even better answers are of course always encouraged!
For a while now I have been a disciple of using Webpack to build my back-end Lambdas after reading James Long's excellent series entitled "Backend Apps with Webpack" (part 1, part2, and part3).
Up until recently, the only version of Node.js that Amazon Web Services offered was 6.10; you had to write your Lambda fn in the "callback" style. But on April 2, 2018 AWS announced that 8.10 was now supported, and with it the suggested pattern is async / await which is great! Until it immediately broke my Webpack build. After a bit of debugging, I can break my build just by adding one async fn to the Lambda handler (I don't even need to call it):
async function firstAsync() {
return true;
}
exports.handler = async (event) => {
// TODO implement
return 'Hello from Lambda!'
};
To be clear, doing this in the AWS Lambda console is perfectly fine, runs great. Webpack even builds it successfully, but upon uploading to AWS Lambda, I get the following error message: regeneratorRuntime is not defined. My code is below. What am I needing to do?
webpack.config.js
const nodeExternals = require('webpack-node-externals');
const path = require('path');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const webpack = require('webpack');
const config = {
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
library: 'index',
libraryTarget: 'commonjs2',
filename: 'index.js'
},
target: 'node', // building for a Node environment
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
module: {
rules: [{
test: /\.(js|jsx)$/,
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
}]
},
plugins: [
new UglifyJsPlugin()
]
};
module.exports = config;
package.json
{
"name": "lambda-webpack",
"version": "1.0.0",
"description": "An empty project scaffold to enable webpack builds in AWS Lambda",
"main": "index.js",
"scripts": {
"build": "webpack",
"upload": "upload.bat"
},
"author": "Geek Stocks®",
"license": "MIT",
"devDependencies": {
"aws-sdk": "^2.179.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-preset-env": "^1.6.1",
"uglifyjs-webpack-plugin": "^1.1.6",
"webpack": "^3.10.0",
"webpack-node-externals": "^1.6.0"
}
}
Geek Stock's answer above is only necessary when using the Node v6.10 runtime. It allows you to use async/await syntax and babel-runtime/regenerator converts your async functions to ES6 generators which is supported on Node v4.3.2 and newer runtimes.
In Node v8.10 though, it is different. async/await is already supported so you don't need Babel to convert your async functions to generators. You just use it correctly and it works.
As for your specific situation, I assume you simply changed your Javascript code to use async/await code but you didn't tell Babel NOT to convert your async/await code to generators. That is why babel-runtime is complaining about a missing plugin.
If this is the case, you simply need to configure Babel to simply target Node v8.10. You can do it like this in your .babelrc...
{
"presets": [
[
"env",
{
"targets": {
"node": "8.10"
}
}
]
]
}
babel will then stop converting those async functions. And since it's not doing a conversion, it will not need the regenerator-runtime anymore.
In my case I'm using it with nodejs12.x. I'm receiving the error regeneratorRuntime is not defined.
I was using preset es2015 and stage-0 with a node12.x code. Also I'm using an older version of babel.
What I did, installed:
"#babel/cli": "^7.10.1",
"#babel/core": "^7.10.2",
"#babel/preset-env": "^7.10.2"
And then set this babel preset:
"presets": [
["#babel/preset-env", {"targets": { "node": "current" }}]
]
Thanks,
To begin using async / await in your Webpack-built code, you need a little help from Babel, specfically the babel-runtime and the babel-plugin-transform-runtime. Fortunately there is a really good writeup on the installation and use of both here on the Babel website. You need Babel to do the following for you:
Automatically requires babel-runtime/regenerator when you use
generators/async functions.
I won't repeat what has been written there, however, of particular note is HOW you need to install these, because while their writeup certainly works for most, there is a needed tweak for some AWS Lambda devs who have not needed runtime dependencies before now.
The first part is pretty normal, you need new devDependencies:
npm install --save-dev babel-plugin-transform-runtime
And also you need to tweak your .babelrc file like they describe:
{
"plugins": [
["transform-runtime", {
"helpers": false,
"polyfill": false,
"regenerator": true,
"moduleName": "babel-runtime"
}]
]
}
But here is the kicker, and this is new to the code above: the babel-runtime is a regular dependencies, not a devDependencies:
npm install --save babel-runtime
These 2 installs and the .babelrc tweaks do SOLVE the async / await problem described above, but it introduces a new problem to the build above: Cannot find module 'babel-runtime/regenerator'.
If you are at all concerned with keeping your Webpack built code small, you are likely also using webpack-node-externals like the above code does. For example, the aws-sdk for JavaScript in Node is very large and is already available in the Lambda environment, so its superfluous to bundle it again. The webpack-node-externals configuration above configures Webpack to ignore ALL the modules in node-modules by default, and there is the root of the new problem. The newly installed babel-runtime is a module that needs to be bundled in the build in order for Lambda to run correctly.
Understanding the problem then, the answer becomes simple: don't use the default configuration. Instead of passing in nothing to webpack-node-externals, configure it like this:
externals: [nodeExternals({
whitelist: [
'babel-runtime/regenerator',
'regenerator-runtime'
]
})], // ignore all modules in node_modules folder EXCEPT the whitelist
And that solves both the original async / await problem, and the (possible) new problem you may be encountering if you had no previous dependencies in your build. Hope that helps — happy Lambda awaiting!

How to get semantic/gulp/webpack to work in electron-react-boilerplate

I am trying to port a react app to electron using electron-react-boilerplate but I'm using semantic-ui which suggested being set up with gulp. electron-react-boilerplate uses webpack to handle all of its packaging and I can't get webpack +gulp to work so everything will package in the electron app.
I'm trying this link that explains how to pipe webpack configs through gulp tasks but I'm getting an "unexpected token import" error from the webpack config.
.babelrc
{
"presets": ["es2015", "stage-0", "react"],
"plugins": ["add-module-exports"],
"env": {
"production": {
"presets": ["react-optimize"],
"plugins": ["babel-plugin-dev-expression"]
},
"development": {
"plugins": ["tcomb"],
"presets": ["react-hmre"]
},
"test": {
"plugins": [
["webpack-loaders", { "config": "webpack.config.test.js", "verbose": false }]
]
}
}
}
simple gulpfile.js straight from the link above:
var gulp = require('gulp');
var webpack = require('webpack-stream');
gulp.task('default', function() {
return gulp.src('src/entry.js')
.pipe(webpack())
.pipe(gulp.dest('dist/'));
});
the webpack dev file is here,
note some of the names are changed between this boilerplate version and my project but otherwise it's the same.
the error:
Configurator>gulp
[09:52:40] Using gulpfile C:\git\Configurator\gulpfile.js
[09:52:40] Starting 'default'...
[09:52:40] 'default' errored after 8.28 ms
[09:52:40] C:\git\Configurator\webpack.config.development.js:7
import webpack from 'webpack';
^^^^^^
SyntaxError: Unexpected token import
at Object.exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:513:28)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Gulp.<anonymous> (C:\git\Configurator\gulpfile.js:7:18)
at module.exports (C:\git\Configurator\node_modules\orchestrator\lib\runTask.js:34:7)
the internet tells me that getting rid of the import errors should be as simple as using the 'es2015' preset in .babelrc but it's there and it's not helping.
I can get the dev server to work in the electron app with the semantic-ui stuff after the initial gulp build for semantic, but for some reason it doesn't build into the electron package when I try to package an installer to deploy this thing.
When I run the electron app dev server through webpack it works fine though, except I get two errors:
cannot set property exports of undefined
and
locals[0] does not appear to be a module object with hot module replacement API enabled
the latter stacktrace goes back to some semantic imports in one of my react files.
I'm totally at a loss as to how to make all this stuff work together.

Resources