trouble with modules in repl - node.js

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?

Related

Await in NodeJS in script vs runkit [duplicate]

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()

googleapis-common throwing error in UUID dependency

I'm trying to get a very basic oauth example to work in a node.js app with express and googleapis. Upon running the application it throws a TypeError inside the UUID dependency which is included with the googleapis-common module. I'm getting a bit frustrated at this point because I have not been able to find any additional information about this to allow me to resolve it myself.
Take a look at the screenshot below for the specifics:
Here it is in text if that makes things easier:
Exception has occurred: TypeError: Cannot assign to read only property 'name' of function 'function generateUUID(value, namespace, buf, offset) {
if (typeof value === 'string') {
value = strin...<omitted>... }'
at _default (C:\Users\ficar\OneDrive\Desktop\Frontend\node_modules\googleapis-common\node_modules\uuid\dist\v35.js:71:23)
at Object.<anonymous> (C:\Users\ficar\OneDrive\Desktop\Frontend\node_modules\googleapis-common\node_modules\uuid\dist\v3.js:14:27)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Module.require (internal/modules/cjs/loader.js:1025:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.<anonymous> (C:\Users\ficar\OneDrive\Desktop\Frontend\node_modules\googleapis-common\node_modules\uuid\dist\index.js:63:34)
at Module._compile (internal/modules/cjs/loader.js:1137:30)
The file this is being thrown in is called "v35.js".
My initial thought is that I must be missing some additional library that interprets the logic throwing the error differently. Eager to learn more about this and find a resolution.
Looks like this is how the uuid module works
node_modules/uuid/dist/v35.js
function _default(name, version, hashfunc) {
function generateUUID(value, namespace, buf, offset) {
...
} // Function#name is not settable on some platforms (#270)
try {
generateUUID.name = name; // eslint-disable-next-line no-empty
} catch (err) {} // For CommonJS default export support
...
Authors warn (comment on line 4), that name property may not be settable and bypass it with empty catch

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

proper way of using es6 classes in a nodejs project

I'd like to be able to use the cool es6 classes feature of nodejs 4.1.2
I created the following project:
a.js:
class a {
constructor(test) {
a.test=test;
}
}
index.js:
require('./a.js');
var b = new a(5);
as you can see I create a simple class that it's constructor gets a parameter. and in my include i require that class and create a new object based on that class. pretty simple.. but still i'm getting the following error:
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/ufk/work-projects/bingo/server/bingo-tiny/index.js:1:63)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
any ideas why ?
Or you can run like this:
node --use_strict index.js
i'm still confused about why 'use strict' is needed, but this is the code that works:
index.js:
"use strict";
var a = require('./a.js');
var b = new a(5);
a.js:
"use strict";
class a {
constructor(test) {
a.test=test;
}
}
module.exports=a;

Resources