Loading React Native: UnhandledPromiseRejectionWarning: Error: Cannot find module 'View' - javascript

I'm trying to contribute to a testing library. The library should provide a wrapper for react-test-renderer like react-native-testing-library does.
In order to see if my code worked I wrote a simple unit test using the code I wrote for the library. Since this was the first test for React Native I added react-native as a dev dependency together with metro-react-native-babel-preset. Furthermore, I added the preset to babel.
{
"presets": [
[
"env",
{
"targets": {
"browsers": ["last 2 versions", "safari >= 7"]
}
}
],
"react",
"module:metro-react-native-babel-preset"
]
}
The library does its assertions using tape.
Now, every test (npm test) throws the error:
> node -r babel-register -r babel-polyfill source/test
/path/to/node_modules/babel-core/lib/transformation/file/options/option-manager.js:328
throw e;
^
Error: Couldn't find preset "module:metro-react-native-babel-preset" relative to directory
When I remove the preset from the babel config, I get the error:
(node:1841) UnhandledPromiseRejectionWarning: Error: Cannot find module 'View'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
at Function.Module._load (internal/modules/cjs/loader.js:507:25)
at Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.get View [as View] (/path/to/node_modules/react-native/Libraries/react-native/react-native-implementation.js:165:12)
at _callee7$ (/path/to/source/test.js:110:6)
at tryCatch (/path/to/node_modules/babel-polyfill/node_modules/regenerator-runtime/runtime.js:65:40)
at Generator.invoke [as _invoke] (/path/to/node_modules/babel-polyfill/node_modules/regenerator-runtime/runtime.js:303:22)
at Generator.prototype.(anonymous function) [as next] (/path/to/node_modules/babel-polyfill/node_modules/regenerator-runtime/runtime.js:117:21)
at step (/path/to/source/test.js:27:191)
(node:1841) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)
(node:1841) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
not ok 10 test exited without ending
---
operator: fail
at: process.<anonymous> (/path/to/node_modules/tape/index.js:90:19)
stack: |-
Error: test exited without ending
at Test.assert [as _assert] (/path/to/node_modules/tape/lib/test.js:226:54)
at Test.bound [as _assert] (/path/to/node_modules/tape/lib/test.js:77:32)
at Test.fail (/path/to/node_modules/tape/lib/test.js:319:10)
at Test.bound [as fail] (/path/to/node_modules/tape/lib/test.js:77:32)
at Test._exit (/path/to/node_modules/tape/lib/test.js:191:14)
at Test.bound (/path/to/node_modules/tape/lib/test.js:77:32)
at process.<anonymous> (/path/to/node_modules/tape/index.js:90:19)
at process.emit (events.js:194:15)
How can I get React Native components to run in my test in a library (and outside of an expo init or react-native init project?
EDIT: I found out that the repo is using Babel 6, which is why the metro preset doesn't seem to work. So I exchanged it for babel-preset-react-native and now I'm back to the initial error that View can't be found.
EDIT 2: package.json
"scripts": {
"lint": "eslint source && echo 'Lint complete.'",
"typecheck": "npx -p typescript tsc --rootDir . source/test.js --allowJs --checkJs --noEmit --lib es6 --jsx react && echo 'TypeScript check complete.'",
"ts": "npm run -s typecheck",
"test": "node -r babel-register -r babel-polyfill source/test",
"watch": "watch 'clear && npm run -s test | tap-nirvana && npm run -s lint && npm run -s typecheck' source",
"precommit": "npm run -s test && npm run -s lint && npm run -s typecheck"
},
"devDependencies": {
"#types/node": "10.12.27",
"babel-cli": "6.26.0",
"babel-eslint": "10.0.1",
"babel-preset-env": "1.7.0",
"babel-preset-react": "6.24.1",
"babel-preset-react-native": "4.0.1",
"babel-register": "6.26.0",
"eslint": "5.14.1",
"eslint-plugin-react": "7.12.4",
"react": "16.8.3",
"react-native": "0.58.5",
"tap-nirvana": "1.1.0",
"typescript": "3.3.3333",
"watch": "1.0.2"
},
"dependencies": {
"cheerio": "1.0.0-rc.2",
"esm": "3.2.6",
"react-dom": "16.8.3",
"react-test-renderer": "16.8.3",
"tape": "4.10.1"
}
EDIT 3:
Sorry, apparently I didn't include my code, even though it is a helpful for solving this problem. It's pretty basic. I'm just trying to render a <View /> using ReactTestRenderer.
import TestRenderer from 'react-test-renderer';
import { Text, View } from 'react-native';
import { describe } from 'riteway';
describe('renderReactNativeComponent', async assert => {
const text = 'Foo';
const component = TestRenderer.create(
<View>
<Text>{text}</Text>
</View>
);
console.log(Text);
assert({
given: 'A React Native component',
should: 'return a working react test renderer instance',
actual: component.findByType('text'),
expected: text
});
});

According to the docs, "Starting from react-native version 0.38, a Jest setup is included by default when running react-native init.".
And
"react-native ships with a Jest preset, so the jest.preset field of your package.json should point to react-native. The preset is a node environment that mimics the environment of a React Native app. Because it doesn't load any DOM or browser APIs, it greatly improves Jest's startup time."
The point is that Jest is supposed to work with React-Native, and riteway isn't. When you run react-native init the following dependency is added: "jest-react-native". And a jest preset is added to package.json:
"jest": {
"preset": "react-native"
}
Apparently there isn't any preset for riteway yet.

Remove node modules and install again
rm -rf node_modules
npm install

You are not returning anything, You need to return a "View"

You might want to just use the suggested example in https://reactjs.org/docs/test-renderer.html just to make sure nothing wrong with code you have written, then add up your own logic to improve it (Just an idea to debug it). May be add it up in https://snack.expo.io? or github, I will help you debug.

Related

npm Node.js Error: No native build was found M2 MacBook

I got this error on my M2 MacBook, running a project, that worked on my old Intel MacBook. Do you have any idea what the problem is?
I am using bun but npm run dev (node 18) gives me the same error.
The exact same error occurred on other projects.
Package.json dependencies:
"devDependencies": {
"#types/three": "^0.143.1",
"parcel": "^2.7.0"
},
"dependencies": {
"three": "^0.143.0"
}
Console output for bun run dev:
$ parcel src/index.html --open
Error: No native build was found for platform=darwin arch=x64 runtime=node abi=108 uv=1 libc=glibc node=18.7.0
loaded from: /Users/frankmayer/Documents/Git/WorldArchitect/WebGLPreview/node_modules/lmdb and package: #lmdb/lmdb-darwin-x64
at load.path (/Users/frankmayer/Documents/Git/WorldArchitect/WebGLPreview/node_modules/node-gyp-build-optional-packages/index.js:64:9)
at Object.load [as default] (/Users/frankmayer/Documents/Git/WorldArchitect/WebGLPreview/node_modules/node-gyp-build-optional-packages/index.js:20:30)
at Object.<anonymous> (/Users/frankmayer/Documents/Git/WorldArchitect/WebGLPreview/node_modules/lmdb/dist/index.cjs:47:47)
at Module._compile (/Users/frankmayer/Documents/Git/WorldArchitect/WebGLPreview/node_modules/v8-compile-cache/v8-compile-cache.js:192:30)
at Module._extensions..js (node:internal/modules/cjs/loader:1174:10)
at Module.load (node:internal/modules/cjs/loader:998:32)
at Module._load (node:internal/modules/cjs/loader:839:12)
at Module.require (node:internal/modules/cjs/loader:1022:19)
at require (/Users/frankmayer/Documents/Git/WorldArchitect/WebGLPreview/node_modules/v8-compile-cache/v8-compile-cache.js:159:20)
at _lmdb (/Users/frankmayer/Documents/Git/WorldArchitect/WebGLPreview/node_modules/#parcel/cache/lib/LMDBCache.js:61:39)
Script error "dev" exited with 1 status
Thanks in advance!
You can override a version using the override option in you package.json.
Read more about this option here: https://docs.npmjs.com/cli/v8/configuring-npm/package-json#overrides
For me, the solution was to add this to my package.json:
"overrides": {
"lmdb": "2.6.0-alpha6",
"#lmdb/lmdb-darwin-arm64": "2.6.0-alpha6",
"#lmdb/lmdb-darwin-x64": "2.6.0-alpha6",
}
This feature is currently (Aug. 2022) not supported by bun!
Yarn does this using resolutions: https://classic.yarnpkg.com/lang/en/docs/selective-version-resolutions

TypeError: createTestCafe is not a function

I am getting this error when I copied runner code from TestCafe site and try to run it. I have testcafe 1.6.0 on Ubuntu 18.04
Below is my runner,
const createTestCafe = require('/usr/local/bin/testcafe');
let testcafe = null;
createTestCafe('localhost', 1337, 1338)
.then(tc => {
testcafe = tc;
const runner = testcafe.createRunner();
return runner
//.src(['__test__/*.js', 'tests/func/fixture3.js'])
//.browsers(['chrome:headless --no-sandbox --disable-gpu', 'safari'])
.src(['./__tests__/testcafe1.js'])
.browsers(['chrome'])
.run();
})
.then(failedCount => {
console.log('Tests failed: ' + failedCount);
testcafe.close();
});
Below is my package.json
{
"private": true,
"scripts": {
"test": "testcafe 'chrome:headless --no-sandbox' ./__tests__/*.js --hostname localhost"
},
"devDependencies": {
"chalk": "^2.4.2",
"prettier": "^1.18.2",
"testcafe": "*",
"rimraf": "^2.6.3"
}
}
Below is the error:
ERROR Cannot prepare tests due to an error.
TypeError: createTestCafe is not a function
at Object.createTestCafe (/app/code/testcafe_runner.js:6:1)
at Function._execAsModule (/usr/local/lib/node_modules/testcafe/src/compiler/test-file/api-based.js:50:13)
at ESNextTestFileCompiler._runCompiledCode (/usr/local/lib/node_modules/testcafe/src/compiler/test-file/api-based.js:150:42)
at ESNextTestFileCompiler.execute (/usr/local/lib/node_modules/testcafe/src/compiler/test-file/api-based.js:174:21)
at ESNextTestFileCompiler.compile (/usr/local/lib/node_modules/testcafe/src/compiler/test-file/api-based.js:180:21)
at Compiler._getTests (/usr/local/lib/node_modules/testcafe/src/compiler/index.js:86:31)
at Compiler._compileTestFiles (/usr/local/lib/node_modules/testcafe/src/compiler/index.js:98:35)
at Compiler.getTests (/usr/local/lib/node_modules/testcafe/src/compiler/index.js:111:34)
at Bootstrapper._getTests (/usr/local/lib/node_modules/testcafe/src/runner/bootstrapper.js:81:26)
at Bootstrapper._bootstrapParallel (/usr/local/lib/node_modules/testcafe/src/runner/bootstrapper.js:214:39)
I'm following the code from Testcafe https://devexpress.github.io/testcafe/documentation/using-testcafe/programming-interface/runner.html
What am I doing wrong here?
You try to require TestCafe's executable file instead of the TestCafe's library. Likely it is located in /usr/lib/node_modules/testcafe or in /usr/local/lib/node_modules/testcafe. You can use the following command to find the path to your globally installed modules:
npm ls -g
However, it's really better to install TestCafe locally if you want to use it as a library. If you plan to run and distribute your test runner script as a standalone CLI tool, you can achieve it with creating a NPM package and adding your runner script to the bin section in package.json: https://docs.npmjs.com/files/package.json#bin
You forgot the keyword function
function createTestCafe(...)

Unable to deploy Solidity contract to Rinkeby network (Invalid asm.js: Invalid member of stdlib)

I've been learning Solidity using this course by Stephen Grider and it's been going well until now, where I am trying to deploy my code to the Rinkeby test network.
For reference, I am using Node version 11.15.0 with npm version 6.7.0 with these dependencies:
"dependencies": {
"ganache-cli": "^6.4.3",
"mocha": "^6.1.4",
"nan": "^2.14.0",
"scrypt": "^6.0.3",
"solc": "^0.4.25",
"truffle": "^4.1.15",
"truffle-hdwallet-provider": "0.0.4",
"web3": "^1.0.0-beta.35" }
I have spent hours switching between versions of Node.js, npm, and all sorts of combinations of the dependencies, from the most current versions to the versions specified in the course. While I am getting a multitude of issues, the most prominent two seem to be
(node:32436) V8: C:\Desktop\solidity\inbox\node_modules\solc\soljson.js:3 Invalid asm.js: Invalid member of stdlib
and
C:\Desktop\solidity\inbox\node_modules\solc\soljson.js:1
var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath["normalize"](filename);var ret=nodeFS["readFileSync"](filename);if(!ret&&filename!=nodePath["resolve"](filename)){filename=path.joi
Error: CONNECTION ERROR: Couldn't connect to node rinkeby.infura.io/v3/acb10732334e4450ba7dc55e618eb70a.
at Object.InvalidConnection (C:\Desktop\solidity\inbox\node_modules\truffle-hdwallet-provider\node_modules\web3\lib\web3\errors.js:28:16)
at HttpProvider.sendAsync (C:\Desktop\solidity\inbox\node_modules\truffle-hdwallet-provider\node_modules\web3\lib\web3\httpprovider.js:129:25)
at Web3Subprovider.handleRequest (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\subproviders\web3.js:13:17)
at next (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\index.js:95:18)
at FilterSubprovider.handleRequest (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\subproviders\filters.js:87:7)
at next (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\index.js:95:18)
at HookedWalletSubprovider.handleRequest (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\subproviders\hooked-wallet.js:109:7)
at next (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\index.js:95:18)
at Web3ProviderEngine._handleAsync (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\index.js:82:3)
at Web3ProviderEngine._fetchBlock (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\index.js:191:8)
at Web3ProviderEngine._fetchLatestBlock (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\index.js:167:8)
at Web3ProviderEngine._startPolling (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\index.js:144:8)
at Web3ProviderEngine.start (C:\Desktop\solidity\inbox\node_modules\web3-provider-engine\index.js:38:8)
at new HDWalletProvider (C:\Desktop\solidity\inbox\node_modules\truffle-hdwallet-provider\index.js:46:15)
at Object.<anonymous> (C:\Desktop\solidity\inbox\deploy.js:6:18)
at Module._compile (internal/modules/cjs/loader.js:816:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
at Module.load (internal/modules/cjs/loader.js:685:32)
at Function.Module._load (internal/modules/cjs/loader.js:620:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:877:12)
at internal/main/run_main_module.js:21:11
My question would be are there any fixes for either of these issues based on my code, or is there a simpler way to deploy to the blockchain? Thank you in advance.
Error: CONNECTION ERROR: Couldn't connect to node rinkeby.infura.io/v3/acb10732334e4450ba7dc55e618eb70a.
You probably meant https://rinkeby.infura.io/... (You're missing the https://.)
I am following the same tutorial as the OP. If you are using node v14.15.4 and npm v6.14.10, I would like to confirm that the following package.json solved the issue:
{
"name": "inbox",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"author": "",
"license": "ISC",
"dependencies": {
"ganache-cli": "^6.4.3",
"mocha": "^6.1.4",
"solc": "^0.4.25",
"truffle-hdwallet-provider": "0.0.4",
"web3": "^1.0.0-beta.35"
}
}
Then rebuild your dependencies by deleting your node_modules of your project, then run
npm install
There may be a problem with the version of the relevant library file, please run the following command.
npm install solc
My npm version is 7.20.3
In my case, the problem was that in the https://infura.io site dropdown what I selected was MAINNET instead of RINKEBY which is an ethereum test network.

Error: Could not locate the bindings file better-sqlite3.node

The Problem
There are some problem with maybe my installation of better-sqlite3 because when I try to execute my index.js (click to show it on pastebin) with
node index.js
there is always the same result. I tried on MacOS, it works but in my machine Linux Lite Ubuntu based distro aren't it gave me the following same error:
/home/mp8/webproject/electron-better-sqlite/node_modules/bindings/bindings.js:96
throw err
^
Error: Could not locate the bindings file. Tried:
→ /home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/build/better_sqlite3.node
→ /home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/build/Debug/better_sqlite3.node
→ /home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/build/Release/better_sqlite3.node
→ /home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/out/Debug/better_sqlite3.node
→ /home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/Debug/better_sqlite3.node
→ /home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/out/Release/better_sqlite3.node
→ /home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/Release/better_sqlite3.node
→ /home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/build/default/better_sqlite3.node
→ /home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/compiled/8.11.3/linux/x64/better_sqlite3.node
at bindings (/home/mp8/webproject/electron-better-sqlite/node_modules/bindings/bindings.js:93:9)
at Object.<anonymous> (/home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/lib/database.js:4:40)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/home/mp8/webproject/electron-better-sqlite/node_modules/better-sqlite3/index.js:2:18)
What is my purpose?
I want to use better-sqlie33 as my database because sqlite3 doesn't gave the node 8.x and later support.
What I tried:
This trouble shooting guide number one and two, but I still had the same error.
make init, first installed better-sqlite3 gave me the error file make/makefile not found. I got the same error when I do npm install better-sqlite3 --save
Make sure better_sqlite3.node are on my node-modules path. yeah it isn't there.
What I want?
I want to run my index.js correctly like I ran it on Mac.
Dependecies
package.json after make init, if not it just a better-sqlite3 dependencies
{
"_from": "better-sqlite3",
"_id": "better-sqlite3#4.1.4",
"_inBundle": false,
"_integrity": "sha512-Y11HN9PQ9YUeKFMrmiHyOLAKElk2ATJzBZJvuzNwTMxoS7vUEEyLnUCtcBFqViLwbomr0RQwp2MBy/ogxF50PA==",
"_location": "/better-sqlite3",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "better-sqlite3",
"name": "better-sqlite3",
"escapedName": "better-sqlite3",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-4.1.4.tgz",
"_shasum": "9fe1dcf7b699087b98b1997cbb00261e265897e2",
"_spec": "better-sqlite3",
"_where": "/home/mp8/webproject/electron-better-sqlite",
"author": {
"name": "Joshua Wise",
"email": "joshuathomaswise#gmail.com"
},
"bugs": {
"url": "https://github.com/JoshuaWise/better-sqlite3/issues"
},
"bundleDependencies": false,
"dependencies": {
"bindings": "^1.3.0",
"integer": "^1.0.5"
},
"deprecated": false,
"description": "The fastest and simplest library for SQLite3 in Node.js.",
"devDependencies": {
"benchmark": "^2.1.4",
"chai": "^4.1.2",
"cli-color": "^1.2.0",
"fs-extra": "^5.0.0",
"mocha": "^4.1.0",
"sqlite": "^2.9.0"
},
"gypfile": true,
"homepage": "http://github.com/JoshuaWise/better-sqlite3",
"keywords": [
"sql",
"sqlite",
"sqlite3",
"custom",
"aggregate",
"database",
"transactions"
],
"license": "MIT",
"name": "better-sqlite3",
"repository": {
"type": "git",
"url": "git://github.com/JoshuaWise/better-sqlite3.git"
},
"scripts": {
"benchmark": "node benchmark",
"install": "node-gyp rebuild",
"install-debug": "node-gyp rebuild --debug",
"lzz": "lzz -hx hpp -sx cpp -k BETTER_SQLITE3 -d -hl -sl -e ./src/better_sqlite3.lzz",
"posttest": "rm -r ./temp/",
"prepublishOnly": "npm run lzz",
"pretest": "rm -r ./temp/ || true && mkdir ./temp/",
"rebuild": "npm run lzz && node-gyp rebuild",
"rebuild-debug": "npm run lzz && node-gyp rebuild --debug",
"test": "$(npm bin)/mocha --bail --timeout 5000 --slow 5000"
},
"version": "4.1.4"
}
my machine
Linux Lite 4.0, Ubuntu Based.
NVM (Node version Manager)
Node 8.11.1
NPM 5.6
I had a problem that looks like your problem
just try that:
projectToto > $ sudo rm -rf node_modules/
projectToto > $ npm install bindings
npm about binding -> https://www.npmjs.com/package/bindings
I ran into a similar situation until I realized I hadn't explicitly installed build-tools on that machine. Here's what resolved it for me (Ubuntu) when run from inside the project directory
$ rm -rf node_modules/
$ rm package-lock.json
$ npm install build-tools -g
$ npm install
For me, the problem turned out to be a circular dependency in my project (angular 10.1.1, node 12.22.6).
Figuring that out was a little tricky. The Angular compiler gave multiple "WARNING in Circular dependency detected: ..." errors, but none of them included the files where the error was actually introduced. I had to walk the project back until a commit where the problem didn't occur, then investigate what changed. That change seemed pretty innocuous - one file exported a constant that was imported by another. Changing the direction of that export solved the problem.
If nothing works....
create a new folder :
install a fresh copy with npm, which will create node_module folder with all the required files.
copy node_module folder and replace with the existing project node_module folder.
close cmd
restart server.
And it worked for me....

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