Await in NodeJS in script vs runkit [duplicate] - node.js

I have node 14.13.0, and even with --harmony-top-level-await, top-level await is not working.
$ cat i.js
const l = await Promise.new(r => r("foo"))
console.log(l)
$ node -v
v14.13.0
$ node --harmony-top-level-await i.js
/Users/karel/i.js:1
const l = await Promise.new(r => r("foo"))
^^^^^
SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:1001:16)
at Module._compile (internal/modules/cjs/loader.js:1049:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:791:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
What am I doing wrong?

Top-level await only works with ESM modules (JavaScript's own module format), not with Node.js's default CommonJS modules. From your stack trace, you're using CommonJS modules.
You need to put "type": "module" in package.json or use .mjs as the file extension (I recommend using the setting).
For instance, with this package.json:
{
"type": "module"
}
and this main.js:
const x = await Promise.resolve(42);
console.log(x);
node main.js shows 42.
Side note: You don't need --harmony-top-level-await with v14.13.0. Top-level await is enabled by default in that version (it was enabled in v14.8.0).

T.J. Crowder answer is right, but I recommend changing all the .js to .mjs
For example, if you are working with NextJS like me, you will see a problem that files in the .next directory use CommonJS (.next is generated using npx next build) and their extensions are js so it raises an error when the .next files use require()

Related

trouble with modules in repl

i am having a hell of time trying to set up a custom repl app. I did a bunch of googling and managed to wrange the code below and got a working repl shell.
script.js
const repl = require("repl")
function evaluate(command, context, filename, callback) {
callback(null, command)
}
repl.start({
prompt: ": ",
eval: evaluate
});
so after getting this prototype working i decided to add a module to split the routing of the command processing. I made a tracker.js module and required it in my script.js
tracker.js
export default class Tracker {
static Process(command) {
console.log(command)
}
}
script.js added the require statement.
const repl = require("repl")
const Tracker = require("./tracker")
function evaluate(command, context, filename, callback) {
callback(null, command)
}
repl.start({
prompt: ": ",
eval: evaluate
});
after i reran this i got an error saying,
SyntaxError: Unexpected token 'export'
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 Object.<anonymous> (C:\Users\e212034\repository\repl\script.js:2:17)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
PS C:\Users\e212034\repository\repl>
so i went back to google and found some tips saying to add type:module to the package.json. so i did this and reran and now i get this error,
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and 'C:\Users\e212034\repository\repl\package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///C:/Users/e212034/repository/repl/script.js:1:14
at ModuleJob.run (node:internal/modules/esm/module_job:185:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
at async loadESM (node:internal/process/esm_loader:88:5)
at async handleMainPromise (node:internal/modules/run_main:65:12)
PS C:\Users\e212034\repository\repl>
i tried changing the module to .mjs no luck. i tried changing the type to commonjs and the module to .cjs no luck on either.
any ideas on how to resolve this issue?

Why am I getting module not found when I have double and triple checked that it is there?

So I'm trying to search google programmatically, and to do so i'm using the node module google-search-results-nodejs, but despite anything I do I keep getting the error not found. I'm working on gitpod online workspace. I wasn't sure if perhaps this had something to do with it but for the life of me I just can't figure it out, and I've looked elsewhere and can't find anything. I tried to check if perhaps my files were in the wrong location, tried uninstalling all node-modules folder and reinstalling it.
Any ideas
const SearchAPI = require('google-search-results-nodejs');
const search = new SearchAPI.GoogleSearchResults(
"663185d5-API-KEY-76787e11787a9"
);
const params = {
engine: 'google_reverse_image',
image_url: 'https://i.imgur.com/E4cOSLw.jpg',
};
const cb = function (data) {
console.log(data['inline-images']);
};
// here
search.json(params, cb);
Here's the error response:
gitpod /workspace/Copyright-Content-Removal/node_modules $ node app.js
internal/modules/cjs/loader.js:968
throw err;
^
Error: Cannot find module '/workspace/Copyright-Content-Removal/node_modules/app.js'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
at Function.Module._load (internal/modules/cjs/loader.js:841:27)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
EDIT: Just retested it and am getting this https://ibb.co/YPBX5Y1 error message.... Also I attached a video link below
Your app.js is inside node_modules directory -
/workspace/Copyright-Content-Removal/node_modules/app.js
But actually your app.js should be outside the node_modules directory like this -
/workspace/Copyright-Content-Removal/app.js

NextJS - Unexpected Token Import

While integrating react-syntax-highlighter into my next-js project I've used the following code:
import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";
import { okaidia } from "react-syntax-highlighter/dist/esm/styles/prism";
...
<SyntaxHighlighter language="jsx" style={okaidia}>
{some code goes here}
</SyntaxHighlighter>
...
I get the following error upon running npm run dev, but only if I run the page directly.
Unexpected token export
/Users/johndetlefs/repos/tal-gel-framework/node_modules/react-syntax-highlighter/dist/esm/styles/prism/index.js:1
(function (exports, require, module, __filename, __dirname) { export { default as coy } from './coy';
^^^^^^
SyntaxError: Unexpected token export
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.react-syntax-highlighter/dist/esm/styles/prism (/Users/johndetlefs/repos/tal-gel-framework/.next/server/static/development/pages/components.js:7242:18)
at __webpack_require__ (/Users/johndetlefs/repos/tal-gel-framework/.next/server/static/development/pages/components.js:23:31)
at Module../pages/components.js (/Users/johndetlefs/repos/tal-gel-framework/.next/server/static/development/pages/components.js:6839:104)
at __webpack_require__ (/Users/johndetlefs/repos/tal-gel-framework/.next/server/static/development/pages/components.js:23:31)
at Object.3 (/Users/johndetlefs/repos/tal-gel-framework/.next/server/static/development/pages/components.js:7175:18)
at __webpack_require__ (/Users/johndetlefs/repos/tal-gel-framework/.next/server/static/development/pages/components.js:23:31)
at module.exports../js/config/libs/_theme-foundation--colors.js.config.themes.list.name (/Users/johndetlefs/repos/tal-gel-framework/.next/server/static/development/pages/components.js:91:18)
If I navigate to the page via another page then everything works great. If I then refresh the page I get the error.
Removing the line
import { okaidia } from "react-syntax-highlighter/dist/esm/styles/prism";
and removing the style attribute from the component fixes everything, but uses the default prism style, which is not the desired outcome.
Looking around I can see people have similar issues, and that the fix probably has something to do with the next.js.config file, and how the css file is being loaded server-side, but I'm not 100% what to do there.
Assuming the next.js.config file is a part of the solution, here are the current contents.
const withSass = require("#zeit/next-sass");
const withCSS = require("#zeit/next-css");
module.exports = withCSS(
withSass({
webpack(config) {
config.module.rules.push({
test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
use: {
loader: "url-loader",
options: {
limit: 100000
}
}
});
config.module.rules.push({
test: /\.svg$/,
use: ["#svgr/webpack"]
});
return config;
}
})
);
I've tried both with & without withCSS and the issue stays the same.
Any help would be much appreciated! 👍
After digging around for a while, I checked out the npm packages directory and found that there are two types of dists: cjs & esm. The simple fix is just using the cjs dist instead of the esm dist.
import { darcula } from 'react-syntax-highlighter/dist/cjs/styles/prism';
Hope this helps :)

Error while importing one file into another in Node.JS

I am using import while importing some functions from my practice.js file into different.js file.
practice.js file:-
function sum(x,y){
return x+y;
}
const pi = 3.14;
module.exports = {
sum : sum,
pi:pi
};
different.js file:-
import {sum,pi} from "./practice.js";
console.log("2 pie: "+sum(pi,pi));
Now when I am using require, the output is proper and no error is given.
When I am using import, there is this following error:-
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:749:23)
at Object.Module._extensions..js
(internal/modules/cjs/loader.js:816:10)
at Module.load (internal/modules/cjs/loader.js:672:32)
at tryModuleLoad (internal/modules/cjs/loader.js:612:12)
at Function.Module._load (internal/modules/cjs/loader.js:604:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:868:12)
at internal/main/run_main_module.js:21:11
I have asked my colleagues and they told me that this is about ES6 and Babel is not configured in your system.
But I am not sure how to proceed with this. Can anybody please help me how to do it?
Rename your main file (different.js) to different.mjs.
Rename your practice.js file to practice.mjs and make it look like this:
function sum(x, y) {
return x + y;
}
const pi = 3.14;
export {sum, pi};
Then run node --experimental-modules different.mjs to run Node with it's experimental module loader.
You can read more here

Gulp-Sourcemaps, SyntaxError: Unexpected token >

Gulp / npm noobie here.
I'm trying to use gulp-sourcemaps, and for some reason, it crashes on var sourcemaps = require('sourcemaps').(It crash only when this line's in the file)
gulpfile:
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('generateApp', function () {
return gulp.src([some paths...])
.pipe(sourcemaps.init())
.pipe(concat('app.min.js'))
.pipe(uglify())
.pipe(sourcemaps.write())
.pipe(gulp.dest(path...));
});
Error :
C:\Projets\node_modules\strip-bom\index.js:2
module.exports = x => {
^
SyntaxError: 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 Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (C:\Projets\node_modules\gulp-sourcemaps\src\init.js:10:14)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
Has anyone encounter this type of error?
I tried to google it, without any success.
I just started getting the same error and fixed it by replacing the code in C:\Projects\node_modules\strip-bom\index.js with this:
'use strict';
module.exports = function (x) {
if (typeof x !== 'string') {
throw new TypeError('Expected a string, got ' + typeof x);
}
// Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
// conversion translates it to FEFF (UTF-16 BOM)
if (x.charCodeAt(0) === 0xFEFF) {
return x.slice(1);
}
return x;
};
Then, I had to run npm rebuild node-sass to get it to work again. It seems to be an issue with an older version of the Strip-bom node module.
For more info, check this out: https://github.com/sindresorhus/strip-bom/commit/e2a3c3b83706ee5baac284f3862d3f6b9e1564e5
UPDATED ANSWER:
This error is caused by using an older version of Node. The Strip-bom module is now using ES2015 (ES6) syntax which requires Node 5.0+. (See Node's ES2015 support list here)
To test your version of Node, run:
node -v
If it's less than 5.0, you'll need to update it. You can download the newest version of Node here:
https://nodejs.org/en/
After installing the new version of Node, I still needed to run npm rebuild node-sass to get Gulp up and running again.
The former answer will still work if you don't want to update your Node version, however, as Louis pointed out, manually editing node module files is not a best-practice.

Resources