babel 6 async / await: Unexpected token - javascript

Im having trouble getting async / await transforms working.
What am I missing?
My .babelrc:
{
"presets": [ "es2015", "stage-0" ]
}
My package.json (snipped):
{
"babel-core": "^6.1.2",
"babel-plugin-transform-runtime": "^6.1.2",
"babel-preset-es2015": "^6.1.2",
"babel-preset-stage-0": "^6.1.2"
}
Output:
babel src/server
SyntaxError: src/server/index.js: Unexpected token (7:21)
5 |
6 | try {
> 7 | let server = await server('localhost', env.NODE_PORT || 3000)
| ^
8 | console.log(`Server started on ${server.info.uri}`)
9 | } catch (err) {
10 | console.error('Error starting server: ', err)

According to this post you need to have babel-polyfill
Babel 6 regeneratorRuntime is not defined with async/await
Hopefully it'll help you :)
EDIT:
It doesn't have to be babel-polyfill but it's the only one I used.
As Gothdo said: the await keyword has to be in a function scope. Moreover, this function definition has to have the async keyword.
This means that you can not have the await keyword on the top-level scope.

Looks like async/await is only available in babel-preset-stage-3
http://babeljs.io/docs/plugins/preset-stage-3/

You can compile them yourself using the transform-async-to-module-method plugin, this allows you to compile them down to bluebird co-routines which requires ES6 generators (available in node4).
Or if you need to compile it back to ES5 so it's compatible for browsers you can use transform-async-to-generator and facebook's regenerator.
I've written about how to set up your babel config here http://madole.xyz/async-await-es7/

Use the Async to generator transform.
Installation
$ npm install babel-plugin-transform-async-to-generator
Usage
Add the following line to your .babelrc file:
{
"plugins": ["transform-async-to-generator"]
}

It's recommended to upgrade to Babel 7 and use babel-env as opposed to stages (see here: https://github.com/babel/babel-upgrade).
There's a command you can use to upgrade accordingly:
npx babel-upgrade

Related

Module not found: Error: Can't resolve 'crypto'

I am getting the following list of errors when I run ng serve.
My package JSON is as follows:
{ "name": "ProName", "version": "0.0.0", "scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e" }, "private": true, "dependencies": {
"#angular-devkit/build-angular": "~0.12.0",
"#angular/animations": "5.2.10",
"#angular/common": "5.2.10",
"#angular/compiler": "5.2.10",
"#angular/compiler-cli": "5.2.10",
"#angular/core": "5.2.10",
"#angular/forms": "5.2.10",
"#angular/platform-browser": "5.2.10",
"#angular/platform-browser-dynamic": "5.2.10",
"#angular/router": "5.2.10",
"#types/dotenv": "^4.0.3",
"#types/errorhandler": "0.0.32",
"#types/express": "^4.16.0",
"#types/node": "^10.5.1",
"apostille-library": "^7.1.0",
"core-js": "^2.5.4",
"dotenv": "^6.0.0",
"errorhandler": "^1.5.0",
"express": "^4.16.0",
"nem2-sdk": "^0.9.7",
"rxjs": "~6.3.3",
"stream": "0.0.2",
"tslib": "^1.9.0",
"typescript": "^2.9.2",
"zone.js": "~0.8.26" } }
The error I get :
ERROR in ./node_modules/aws-sign2/index.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/aws-sign2' ERROR in
./node_modules/aws4/aws4.js Module not found: Error: Can't resolve
'crypto' in '/Users/MYPC/Documents/Myproj/ProName/node_modules/aws4'
ERROR in ./node_modules/ecc-jsbn/index.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/ecc-jsbn' ERROR in
./node_modules/http-signature/lib/verify.js Module not found: Error:
Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib'
ERROR in ./node_modules/http-signature/lib/signer.js Module not found:
Error: Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/http-signature/lib'
ERROR in ./node_modules/nem-sdk/build/external/nacl-fast.js Module not
found: Error: Can't resolve 'crypto' in
'/Users/MYPC/Documents/Myproj/ProName/node_modules/nem-sdk/build/external'
ERROR in ./node_modules/nem-sdk/node_modules/aws-sign2/index.js
I ran into a similar issue lately while trying to use another library (tiff.js) in a small project I was experimenting with.
The way I got around this was to add the following to my package.json file, right after the devDependencies section.
"devDependencies": {
...
},
"browser": {
"crypto": false
}
This didn't seem to have any adverse effect when trying to use the library in the application.
Adding this setting in tsconfig.json file under that project resolve this warning
"compilerOptions": {
"baseUrl": "./",
"paths": {
"crypto": [
"node_modules/crypto-js"
]
}
I like R. Richards's answer, but I thought it would be useful to provide some more information.
This is a known issue with Angular, and the Angular CLI dev team seems to think it's a feature rather than a bug. I, as well as other developers in this issue thread, disagree. Contributors to that thread provided several workaround fixes, but my project didn't compile successfully until I implemented R. Richards' solution. I didn't revert the previous changes, though, so tacnoman's and GrandSchtroumpf's fixes may be of use to others.
Some, like clovis1122 here and others in that issue thread, have questioned why a web app would need access to these libraries and why the necessary tasks can't be completed on the server side instead. I can't speak for everyone, but my use case is that, when authenticating a user account, Strapi responds with a JSON Web Token string that must be decoded by the client. Since the necessary library depends on crypto and stream, you won't be able to extract the JWT expiration time unless those dependencies are available.
In case anyone has trouble extrapolating from R. Richards' answer, you'll have to set to false any dependencies that are showing up in "can't resolve x" errors. For example, the critical part of my package.json is:
"browser": {
"crypto": false,
"stream": false
}
I thought I would expand on what Tarique Ahmed wrote in his answer.
I was using an npm module that had the following line in the code:
const crypto = require('crypto');
I couldn't add:
"browser": {
"crypto": false
}
to the package.json because the crypto package had to be part of the build.
It turns out that during the compilation process Angular seems to have decided to install the crypto-browserify package instead of crypto.
Adding the following to the tsconfig.json file instructs the build to use the crypto-browserify library every time that crypto is required. As you can see, I had the same issue for the stream package.
"paths": {
"crypto": [
"node_modules/crypto-browserify"
],
"stream": [
"node_modules/stream-browserify"
]
}
After having the same issue with Angular 11 and crypto-js 4 (and manually setting the path in tsconfig.json), I found rolling back crypto-js to version 3.1.9-1 fixed the issue. It seems a change made in version 4 caused the issue.
npm install crypto-js#3.1.9-1
Explained here in repo issues:
GitHub issue
If you upgraded to Webpack 5, you need to add this to your webpack config file:
resolve: {
fallback: { crypto: false },
},
aws-sign2 is a NodeJS package (and crypto is a NodeJS module), but it looks like you're dealing with a web application. It makes sense that the crypto module is not available in that environment.
Would it be possible to complete what you need to do server-side? Otherwise, you may need to look for another package.
For Laravel Inertia JS project, my solution was:
1- Add dependencies to package.json
"dependencies": {
"crypto-browserify": "3.12.0",
"crypto-random-string": "^3.3.0",
"stream": "^0.0.2"
}
2-In webpack.config.js:
const path = require('path');
module.exports = {
resolve: {
alias: {
'#': path.resolve('resources/js'),
},
fallback: {
crypto: require.resolve('crypto-browserify'),
stream: require.resolve('stream'),
},
},
};
3-Install, build and run:
npm install && npm run watch
I have resolved my issue using below steps:
Add below to tsconfig.json to resolve crypto warning:
"paths": {
"crypto": [
"node_modules/crypto-js"
]
},
and add below to angular.json
"options": {
"allowedCommonJsDependencies": [
"crypto-js"
],
...
}
My Error
In my Case the import { get } from "express/lib/response" is the culprit, which is automatically added by vs-code.
So, after removing it I solved my issue
When using #Laravel framework with Laravel Mix this is going to be more trick. I spend some hours on this NPM nightmare and found a solid solution.
So, in your webpack.mix.js you find the 'comment'
/*
|--------------------------------------------------------------------------
| Mix Asset Management
|--------------------------------------------------------------------------
|
| Mix provides a clean, fluent API for defining some Webpack build steps
| for your Laravel application. By default, we are compiling the Sass
| file for the application as well as bundling up all the JS files.
|
*/
Now just below that comment add the following lines;
mix.webpackConfig(webpack => {
return {
plugins: [
new webpack.LoaderOptionsPlugin({
exports: {
resolve: {
fallback: {
crypto: require.resolve('crypto-browserify'),
}
}
}
})
]
};
});
Now you can use Laravel Mix just like you would edit webpack.config.js ;)
Also; In package.json remove:
--no-progress --hide-modules
These are no longer valid for WebPack >= 5. Enjoy!
After a deep a research i found that the solution is very simple: replace
import * as CryptoJS from 'crypto-js'; with declare var CryptoJS;
Using direct import may not work with ES6 Enviornment..
This may help you.
$ npm i crypto-js#latest // For using latest version 4
import AES from 'crypto-js/aes';
import Utf8 from 'crypto-js/enc-utf8';
import { secretKey } from './environments/environment';
/** Encryption */
const data = {key: 'Test Value'};
const ciphertext = AES.encrypt(JSON.stringify(data), secretKey).toString();
console.log('Encrypted Data', ciphertext);
/** Decryption */
const bytes = AES.decrypt(ciphertext, secretKey);
const decryptedData = JSON.parse(bytes.toString(Utf8));
console.log('Decrypted Data', decryptedData);
https://github.com/brix/crypto-js/issues/168#issuecomment-785617218
Add the option allowedCommonJsDependencies with literal "crypto-js" in a array, this in file angular.json:
"architect":
"build": {
"options": {
"allowedCommonJsDependencies": [
"crypto-js"
]
},
}
}
This will disable all warnings, tested in Angular 11.
My problem was that I was trying to build to node and web using the same code, but is not possible to built to web while importing a WebSocket dependency, ws in my case
So the solution is by using a wrapper:
Install a wrapper, I will use isomorphic-ws because is made for ws
npm i --save isomorphic-ws
Remove const WebSocket = require('ws')
Replace with:
const WebSocket = require('isomorphic-ws')
I ended up going into
node_modules/react-scripts/config/webpack.config.js
and adding:
fallback: {
// Here paste
crypto: require.resolve("crypto-browserify"),
https: require.resolve("https-browserify"),
http: require.resolve("stream-http"),
url : require.resolve("url")
}
And now my react app builds with errors but no dependency issues. Ill update this when I get it building.
Add
npm install crypto-js
Or Add a specific version according to your project need
npm install crypto-js#4.0.0
Also, run the above commands in Window "run as administrator" or in Linux use sudo
Alot of answers already but still none of them works. In my case I see warning message
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default. This is no longer the case. Verify if you need this module and configure a polyfill for it. If you want to include a polyfill, you need to: - add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }' - install 'crypto-browserify' If you don't want to include a polyfill, you can use an empty module like this: resolve.fallback: { "crypto": false }
comment from #stewii did helped me to resolved this.
There is now an ES modules version called "crypto-es". It clears these warnings. npmjs.com/package/crypto-es
After this I imported cryptoES
import CryptoES from 'crypto-es';
and remove the existing import of cryptoJs. Re-start the compile and Voila.. The warning message is gone.
I tried a lot of the solutions above but the final thing that worked for me was downloading the crypto-es package and adding, "type":"module" to package.json.
https://www.npmjs.com/package/crypto-es
I was facing same issue, Just run node patch.js and it worked. The issue is, browser doesn't allow server files to be run on browser. In case you need some of these, You can use node patch.js. If you don't want to run any server file on browser, you can simply apply above mentioned solution by #R.Richards. Might be helpful for someone..
In my case, the solution described by R.Richards doesn't work.
However, following several threads along this issue, I finally understood where to insert the recommendation provided in the warning message and solved this warning.
WARNING in ./node_modules/bcryptjs/dist/bcrypt.js 64:13-45
Module not found: Error: Can't resolve 'crypto' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\bcryptjs\dist'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
**If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "crypto": false }**
Differently from many contributors, I didn't want to install crypto-browserify as I don't need it (*), and I chose to add the fallback { "crypto": false }.
However I didn't know where to add this fallback. After reading several threads, I found it was in the webpack.config.js file, which is located in the directory node_modules/react_scripts/config.
Adding this fallback made the compilation succeed without any warning.
(*) PS : I once tried to add the following fallback { "crypto": require.resolve("crypto-browserify") }, but it led to generation of 7 errors, requiring other modules :
Failed to compile.
Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
ERROR in ./node_modules/cipher-base/index.js 2:16-43
Module not found: Error: Can't resolve 'stream' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\cipher-base'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "stream": require.resolve("stream-browserify") }'
- install 'stream-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "stream": false }
ERROR in ./node_modules/readable-stream/lib/_stream_readable.js 43:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/readable-stream/lib/_stream_writable.js 65:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/readable-stream/lib/internal/streams/buffer_list.js 63:15-32
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\readable-stream\lib\internal\streams'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/ripemd160/index.js 3:13-37
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\ripemd160'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/safe-buffer/index.js 3:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safe-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
ERROR in ./node_modules/safer-buffer/safer.js 5:13-30
Module not found: Error: Can't resolve 'buffer' in 'C:\PC\Documents\3 - Projet MAKAO\dev\RepoAlecol\node_modules\safer-buffer'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
If you want to include a polyfill, you need to:
- add a fallback 'resolve.fallback: { "buffer": require.resolve("buffer/") }'
- install 'buffer'
If you don't want to include a polyfill, you can use an empty module like this:
resolve.fallback: { "buffer": false }
webpack compiled with 7 errors
I had this problem in ReactJS with create-react-app(facebook)
Solution:
First install the necessary packages "crypto-browserify"
Modify webpack.config.js in reactjs with create-react-app this file is inside:
node_modules/react-scripts/config/webpack.config.js
Search module.exports and inside this function there is a return:
module.exports = function (webpackEnv) {
...
return {
...
resolve: {
...
fallback: {
// Here paste
crypto: require.resolve("crypto-browserify"),
}
}
}
}
Note: Is possible you need other packages how "stream-browserify" the steps are same. This solution works, but when the webpack project starts it shows warnings
Pd: I am not native speaker English, but I hope understand me.

node.js async await - error regeneratorRuntime

I learnt how to use promises in a browser but when I want to use it in my node.js it throw error.
var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(url) {
^
ReferenceError: regeneratorRuntime is not defined
node version
v10.4.1
I use babel for export and import syntax with settings like here in starting file
require('babel-register')({
presets: [ 'env' ]
})
babel-polyfill is required. You must also install it in order to get async/await working.
Here explain better Babel 6 regeneratorRuntime is not defined
I was unable to use async/await and for me this worked out.
In your babel file include this.
presets: [
[
"#babel/preset-env",
{
"targets": {
"node": "10"
}
}
] ]
Presumably you are trying to use async / await syntax? You will need to install transform-async-to-generator plugin and include it in your Babel config
require('babel-register')({
presets: ['env'],
plugins: ['transform-async-to-generator']
})

SyntaxError: missing ) after argument list, When using async

Why am I getting this error When I use async?
My Code:
bot.onText(/\/start/, async msg => {
const opts = {
parse_mode: 'Markdown' ,
reply_markup: JSON.stringify({
keyboard: StartKeyboard,
resize_keyboard: true,
one_time_keyboard: true
})
};
await bot.sendMessage(msg.chat.id, 'Hi', opts);
});
Error:
bot.onText(/\/start/, async msg => {
^^^^^
SyntaxError: missing ) after argument list
I'm using node.js v6.11.0 with "dependencies":
{ "babel-polyfill": "^6.23.0",
"cheerio": "^1.0.0-rc.2",
"dotenv": "^4.0.0",
"firebase": "^4.1.2",
"firebase-admin": "^5.0.0",
"node-telegram-bot-api": "^0.27.1",
"request": "^2.81.0" },
Your version of NodeJS (6.11 LTS) is too old and does not support the async/await features. The syntax error is a result of the Javascript interpreter not recognizing the async token and getting confused about arguments.
Upgrade to NodeJS 7.6 or later. https://www.infoq.com/news/2017/02/node-76-async-await
In prior versions, the only way to perform asynchronous behaviour is to use promises.
If you don't want to/can't update your node version, try using babel presets.
I had the same error using ES6 with jest (node v6.9.1).
Just add these two modules to your dependencies
npm install --save babel-preset-es2015 babel-preset-stage-0
And add a file .babelrc to your root dir with the following code:
{ "presets": ["es2015", "stage-0"] }
And if you are not using it already, install babel-cli and run your application with babel-node command
sudo npm install -g babel-cli
babel-node app.js
If you're seeing this error with a newer version of Node, it's probably a syntax or some other error before the line Node is pointing out.
For instance, consider the snippet below.
router.get("/", function (req, res, next) {
try {
res.json(await mySvc.myFunc());
} catch (err) {
console.error(err.message);
next(err);
}
});
With node -v reporting v14.17.6, this gives:
myapp $ DEBUG=myapp:* npm start
> myapp#0.0.0 start /home/me/myapp
> node ./bin/www
/home/me/myapp/routes/myroute.js:7
res.json(await mySvc.myFunc());
^^^^^
SyntaxError: missing ) after argument list
The error, of course, is on the first line of the snippet. Adding an async on that line, thus,
router.get("/", async function (req, res, next) {
fixes the issue.

babel - es2015 and es2017 preset not working together

I have two js files : play.js and myStore.js.
I want to import code from myStore.js into play.js and use it there. I'm using es2015 plugin for the import, But it makes my es2017 friendly code fail, even though I have es2017 setup.
play.js:
import G from '../functions/myStore.js'; // import needs es2015
// this works with es2017, but not when es2015 is also included
for(k in [1,2,3]) console.log(k)
myStore.js
var G = {}
export default G
Output: If I did not import anything, and just used the es2017 preset, this would run fine, but using es2015 along with es2017 makes this fail as below:
for (k in [1, 2, 3]) {
^
ReferenceError: k is not defined
I'm executing this from terminal via npm start . Here's my package.json:
{
"name": "functions",
"version": "1.0.0",
"description": "",
"main": "play.js",
"scripts": {
"start": "babel-node play.js"
},
"author": "Somjit",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.24.0",
"babel-preset-es2015": "^6.24.0",
"babel-preset-es2015-node5": "^1.2.0",
"babel-preset-es2017": "^6.22.0"
}
}
and my babel.rc:
{ "presets": ["es2015", "es2017"] }
Ok. My short answer would be...
1) Babel reads your code and if it sees some new js feature it translate it to regular js by using presets. For example, if it sees let a = 1 Babel uses preset-es2015 (that knows what let is) and translate this line into var a = 1 so your browser could understand this line.
2) If you look to the docs of babel-preset-es2017 you'll see that it supports only two features. You have not this features in your code. So babel don't use this preset while reading code that you've provided. So es2017 don't matter in your problem.
3) If you run your code without es2015 it allows you to declare variables without var (because you can do this in js without strict mode). But when you use this preset Babel reads your code and trows an Error because according to new js standarts you need to declare variables with var, let or const and can't just write a = 1;
when I started with babel even small stuff where taking too much time to understand.
then I found this tutorial which helped me a lot.
In Your case, absolutely your problem is not babel-preset-es2017. you must install babel-plugin-transform-runtime and put it in your .babelrc file as plugin.
installing:
npm install --save-dev babel-plugin-transform-runtime
setting .babelrc file:
{
"presets": [
"es2015",
"es2017"
],
"plugins": [
"transform-runtime"
]
}

SyntaxError: Unexpected token function - Async Await Nodejs

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

Categories