use #std/esm to use ES6 in Express node.js project - node.js

I'm working on a Node.js project. I'm trying to use ES6 feature (like "import", "export") with a new ESM library but I'm struggling how to use it in Express app.
Here is what I have done:
Run npm i --save #std/esm in the project directory.
In index.js add "require("#std/esm")" to first line
use ESS "import"
here is my index.js
require("#std/esm")
// const express = require( "express" );
import express from '../node_modules/express'
const router = express.Router();
/* GET home page. */
router.get( "/", ( req, res, next ) => {
res.render( "index", { "title": "Express" } );
} );
// export default router
module.exports = router;
Run the project but I get this error
/usr/local/bin/node /Volumes/Elements/Learning/Node/Project/NodeMongoTest1/routes/index.js
/Volumes/Elements/Learning/Node/Project/NodeMongoTest1/routes/index.js:3
import express from '../node_modules/express'
^^^^^^
SyntaxError: Unexpected token import
at new Script (vm.js:51:7)
at createScript (vm.js:136:10)
at Object.runInThisContext (vm.js:197:10)
at Module._compile (module.js:626:28)
at Object.Module._extensions..js (module.js:673:10)
at Module.load (module.js:575:32)
at tryModuleLoad (module.js:515:12)
at Function.Module._load (module.js:507:3)
at Function.Module.runMain (module.js:703:10)
at startup (bootstrap_node.js:193:16)
Process finished with exit code 1
Any know how to config ESM with Express Node.js?

There are three ways to enable ESM with #std/esm.
Enable ESM with a CJS bridge:
index.js
// Provide options as a parameter, environment variable, or rc file.
require = require("#std/esm")(module/*, options*/)
module.exports = require("./main.mjs").default
Enable ESM in the Node CLI with the -r option:
node -r #std/esm main.mjs
Enable ESM in the Node REPL:
node -r #std/esm
Try #2 first to check whether rest of code is correct in index file

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

Why is my file throwing an error on execution?

I am getting an error when I try to execute a file using the command node database.ts
Can anyone tell me what the issue is with my syntax?
The file looks like:
import { Sequelize } from 'sequelize-typescript';
export const sequelize = new Sequelize({
database : "zemit",
dialect : "postgres",
username : "postgres",
password : "postgres",
host : "localhost",
port : 5432
});
sequelize.authenticate().then(() => {
console.log("Connected to DB");
})
.catch((err) => {
console.log(err);
})
The error says:
import { Sequelize } from 'sequelize-typescript';
^^^^^^
SyntaxError: Cannot use import statement outside a module
?[90m at Module._compile (internal/modules/cjs/loader.js:892:18)?[39m
?[90m at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)?[39m
?[90m at Module.load (internal/modules/cjs/loader.js:812:32)?[39m
?[90m at Function.Module._load (internal/modules/cjs/loader.js:724:14)?[39m
?[90m at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)?[39m
?[90m at internal/main/run_main_module.js:17:11?[39m
node runtime system does not support run a Typescript file file as a .js file. If you are working with Typescript, you have to transpile your .ts files to .js file with command tsc (require Typescript installed), then you run your generated .js file with node database.js command (instead of node database.ts)
Or you can use ts-node - TypeScript execution and REPL for node.js, then you can "run" a .ts file directly, with ts-node database.ts command.
Just replaced all the "imports" with "requires".
I had similar issue, searched online but didn`t got any solution.
Then I replaced import with require and it worked.

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

How do you import a function with parameters using ECMAScrip6?

I am setting up a brand new project in Express using Babel and ESLint, and am trying to setup dynamic routes. The only issue is that I cannot figure out how to call the loader for the routes. This is my current code regarding the loader.
routes/index.js
import fs from 'fs';
/**
* Register Default Routes
* #param {Object} app express.Application
*/
export default function(app) {
fs.readdirSync(__dirname).forEach((fileName) => {
if (fileName == __filename.slice(__dirname.length + 1)) return;
let fileNameStripped = fileName.substring(0, fileName.lastIndexOf('.'));
require('./' + fileNameStripped)(app); // does not work
});
}
index.js
import express from 'express';
import routes from './routes/index.js';
const app = express();
app.use(express.static('public'));
routes(app); // works now
...
Babel Error
TypeError: require(...) is not a function
at /app/build/routes/index.js:1:314
at Array.forEach (<anonymous>)
at exports.default (/app/build/routes/index.js:1:195)
at Object.<anonymous> (/app/build/index.js:1:393)
at Module._compile (module.js:649:30)
at Object.Module._extensions..js (module.js:660:10)
at Module.load (module.js:561:32)
at tryModuleLoad (module.js:501:12)
at Function.Module._load (module.js:493:3)
at Function.Module.runMain (module.js:690:10)
The issue appears to be related to https://github.com/babel/babel/issues/2683
Since nested route files are supposed to be ES modules with default exports, require('./' + fileNameStripped) is module object and not a function. It should be:
require('./' + fileNameStripped).default(app);
Depending on Babel configuration (dynamic-import-node plugin is required), require() can be replaced with dynamic import() but it's less desirable here, because dynamic import is not synchronous and can cause race conditions.

'use-strict' enabled but not working in node

I have enabled use-strict mode in my .js file but when I run it, node keeps telling me that I don't have it enabled. PLEASE don't tell me to write "use-strict"; at the top of my file because I already tried that.
Here is my server.js file. I have been trying to see what is wrong but so far stack overflow has not been much help since most people seem to get this working on their first try.
require('use-strict')
'use-strict';
let util = require('util');
let http = require('http');
let Bot = require('#kikinteractive/kik');
var kik_username = process.env.KIK_USERNAME;
var kik_api_key = process.env.KIK_API_KEY;
var kik_baseUrl = process.env.KIK_BASEURL;
// Configure the bot API endpoint, details for your bot
let bot = new Bot({
username: kik_username,
apiKey: kik_api_key,
baseUrl: kik_baseUrl
});
bot.updateBotConfiguration();
bot.onTextMessage((message) => {
message.reply(message.body);
});
// Set up your server and start listening
let server = http.createServer(bot.incoming()).listen(8085);
Everything seems fine but when I run
$ node server.js
I keep getting this error
let util = require('util');
^^^
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:387:25)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)
at startup (node.js:148:18)
at node.js:405:3
It tells me to enable strict mode BUT I ALREADY DID THAT. I even required an npm package to make sure I was doing it right! Can anyone make sense of what is happening?
No dash in 'use strict'
'use strict' // not 'use-strict'
Check out the documentation for further reference
You don't need to require an npm package. just put "use strict"; at the top of the js file.

Resources