Error while importing one file into another in Node.JS - 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

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?

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

Knex: How to fix "Cannot read property 'prototype' of undefined" on ARM for initial-setup

I am trying to initialize a sqlite3 database with knex on an ARM-Device, but getting the error:
Knex: run
$ npm install sqlite3 --save
TypeError: Cannot read property 'prototype' of undefined
at inherits (/home/user/node_modules/sqlite3/lib/sqlite3.js:27:16)
at Object.<anonymous> (/home/user/node_modules/sqlite3/lib/sqlite3.js:66:1)
at Module._compile (module.js:653:30)
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 Client_SQLite3._driver (/home/user/sWave-Gateway/node_modules/knex/lib/dialects/sqlite3/index.js:79:12)
at Client_SQLite3.initializeDriver (/home/user/sWave-Gateway/node_modules/knex/lib/client.js:254:26)
at Client_SQLite3.Client (/home/user/sWave-Gateway/node_modules/knex/lib/client.js:115:10)
at new Client_SQLite3 (/home/user/sWave-Gateway/node_modules/knex/lib/dialects/sqlite3/index.js:62:20)
at Knex (/home/user/node_modules/knex/lib/index.js:60:34)
at Object.<anonymous> (/home/user/dist/db/knex-data-access-layer/index.js:28:28)
at Module._compile (module.js:653:30)
I already tried to set the NODE_ENV in different ways set the rights of the files with chmod to 777 but nothing worked so far. I am kind of despaired because i have not changed anything on this part for a long time and it suddenly stopped working.
The Command i use:
NODE_ENV=production node dist/initial-setup.js
It executes the following code:
import * as config from 'config';
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as mkdirp from 'mkdirp';
import * as path from 'path';
import { boot } from './boot';
import * as constants from './constants';
import { dataAccessLayer } from './db';
import * as shell from 'shelljs';
// tslint:disable:no-console
boot();
let logPath: string = config.get(constants.CONFIG_LOG_DIR);
if (!fs.existsSync(logPath)) {
console.log(`Creating logs directory at ${logPath} ...`);
mkdirp.sync(logPath);
}
let secretDirPath: string = config.get(constants.CONFIG_SECRET_DIR);
if (!fs.existsSync(secretDirPath)) {
console.log(`Creating secret directory at ${secretDirPath} ...`);
mkdirp.sync(secretDirPath);
}
let jwtSecret: string = crypto.randomBytes(config.get(constants.CONFIG_JWT_RANDOM_BYTES)).toString('hex');
let jwtSecretPath: string = path.join(secretDirPath, config.get(constants.CONFIG_JWT_SECRET_FILE));
fs.writeFileSync(jwtSecretPath, jwtSecret, 'utf8');
async function setupDb(): Promise<void> {
await dataAccessLayer.migrate();
try {
await dataAccessLayer.seed();
} catch (e) {
// ignore missing production seeds, rethrow otherwise
if (e.toString().indexOf('volatile-seeds/production') === -1) {
throw e;
}
}
}
setupDb().catch(e => console.log(e))
.then(()=> {
shell.exec('tskill node');
});
The problem was that the newest sqlite3 4.0.8 version will not work correctly on this ARM-processor. I downgraded it to 4.0.6 and now it works flawless.
I also had this problem when upgrading from sqlite3 version 4.0.4 to version 4.1.0. Pinning my dependency to 4.0.4 got it working again. You can also see some other workarounds here and here, and discussion of usage in browser environments here.

Error:no such file when using fs.outputJsonSync

I have a problem like this. I have created a compile.js file to compile my solidity Contract. In there to handle file I am using the fs-extra module.
This is my compile.js file
const path = require('path');
const solc = require('solc');
const fs = require('fs-extra');
const buildPath = path.resolve(__dirname,'build');
fs.removeSync(buildPath);
const campaignPath= path.resolve(__dirname,'contracts','Campaign.sol');
const source = fs.readFileSync(campaignPath,'utf8');
const output= solc.compile(source,1).contracts;
fs.ensureDirSync(buildPath);
for(let contract in output){
fs.outputJsonSync(
path.resolve(buildPath,contract),
output[contract]
);
}
It works everything finely, without for each loop. When I compile this file with for loop it gives me an error saying that
C:\Users\tharindusa\WebstormProjects\Campaign\node_modules\solc\soljson.js:1
(function (exports, require, module, __filename, __dirname) { var Module;if(!Modu
le)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};fo
r(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[k
ey]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=ty
peof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"
&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var EN
VIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WOR
KER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x)
{process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=funct
ion printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nod
ePath=require("path");Module["read"]=function read(filename,binary){filename=node
Path["normalize"](filename);var ret=nodeFS["readFileSy
Error: ENOENT: no such file or directory, open 'C:\Users\tharindusa\WebstormProje
cts\Campaign\ethereum\build\:Campaign.json'
at Object.fs.openSync (fs.js:646:18)
at Object.fs.writeFileSync (fs.js:1299:33)
at Object.writeFileSync (C:\Users\tharindusa\WebstormProjects\Campaign\node_m
odules\fs-extra\node_modules\jsonfile\index.js:117:13)
at Object.outputJsonSync (C:\Users\tharindusa\WebstormProjects\Campaign\node_
modules\fs-extra\lib\json\output-json-sync.js:15:12)
at Object.<anonymous> (C:\Users\tharindusa\WebstormProjects\Campaign\ethereum\compile.js:15:8)
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)
Can someone help me to solve this problem? .Thank you
Your filename (:Campaign.json) contains a colon, which is invalid in Windows, where colons are only used with drive letters.
I had run into the same problem while compiling my contracts.The issue with your code is that it tries to create a file named :Campaign which is not allowed in windows.
I used the following code to get around it
for(let contract in output){
fs.outputJSONSync(
path.resolve(buildPath,contract.replace(/:/g,'')+'.json'),
output[contract]
);
}

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