Why is my file throwing an error on execution? - node.js

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.

Related

Node - Migrate postgres DB programmatically using jest globalsetup.js file

I am trying to use testcontainers(https://github.com/testcontainers/testcontainers-node/tree/master/src/modules/postgresql) to spin up a postgres db and use that to run my jest tests.
I used globalsetup.js file to run the container spinup code. The container is spinning successfully, no problem in that, but the issue arises when i try to migrate the db. For Migrating i use typeorm's connection.runMigrations function. Somehow the migration is not working.
All my files, except globalsetup.js is a typescript file.
My connection string looks like this:
createConnection({
url: `postgres://${username}:${encodeURIComponent(password)}#${host}:${port}/${database}`
entities: process.env.TYPEORM_ENTITIES.split(‘,’),
migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
type: 'postgres,
});
TYPEORM_ENTITIES=src/db/entities/**/.ts
TYPEORM_MIGRATIONS=src/db/migrations/.ts
and in my jest.globalSetup.js:
const {createConnection} = require('typeorm')
module.exports = async () => {
/* Code for Container Startup */
process.env.NODE_ENV = ‘test’;
const connection = await createConnection({
url: `postgres://uno-test:dia#localhost:${process.env.TYPEORM_PORT}/cart-test?sslmode=disable`,
entities: process.env.TYPEORM_ENTITIES.split(‘,’),
migrations: process.env.TYPEORM_MIGRATIONS?.split(‘,’),
type: ‘postgres’,
});
await connection
.runMigrations()
.then((value) => console.log(‘Migration Done’, value))
.catch((e) => console.log(e));
await connection
.close()
};
Error Message is:
import { Column, CreateDateColumn, Entity, PrimaryGeneratedColumn, UpdateDateColumn } from ‘typeorm’;
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1033:15)
at Module._compile (node:internal/modules/cjs/loader:1069:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159: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 /Users/webmaster/CART/cart-portal-service/node_modules/typeorm/util/ImportUtils.js:29:52
at step (/Users/webmaster/CART/cart-portal-service/node_modules/tslib/tslib.js:144:27)
I tried changing the entities and migrations constants to
TYPEORM_ENTITIES=src/db/entities/**/.{ts,js}
TYPEORM_MIGRATIONS=src/db/migrations/.{ts,js}
If i do above chagne, I no longer see the error, but my db is empty as in no tables are created.
Versions:
Node - 16.6.0
Typeorm - 0.2.45
typescript: 4.7.4
jest: 28.1.3

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

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

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.

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

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

Resources