Import external class in nodejs - node.js

i´v got a class which i want to export and import it in another file.
//db.js
class sqlConn {
constru....
}
modules.exports = sqlConn;
I tried to import it, but that doenst worked for me...
//main.html
var sqlConn = require('path_to_file');
var obj = new sqlConn(...);
That gives me following error:
Uncaught Error: Cannot find module 'path_to_file'
can someone help me?
Edit on some answers
I´m using electron with node.js
and my class is laying on an html server.
Also i´m trying to import all in an index.html to sahre an electron.exe which imports all with ajax.

Pass the good path on the required function :
var sqlConn = require('./db'); // or other path if the file db.js isn't on the same folder
but I see main.html, you try to use a node.js code into html?

If you're using ES6/ES2015 you can import the class:
db.js:
class sqlConn {
...
}
export { sqlConn as default }
main.html:
import sqlConn from './path_to_file');
var obj = new sqlConn(...);

Already tried. Gives me error: Uncaught SyntaxError: Unexpected token import
Did you try the require syntaxt?
const db = require('./db');

Related

Unhandled Runtime Error Error: Configuration must contain `projectId`

I'm getting this error again and again. I've provided projectID as well via env file, still getting
I'm new to NextJS and sanity as well, please help me out, your help will be appreciated.
import sanityClient from '#sanity/client';
import imageUrlBuilder from '#sanity/image-url';
export const client = sanityClient({
projectId: process.env.NEXT_APP_PROJECT_ID,
dataset: 'production',
apiVersion: '2022-03-10',
useCdn: true,
token: process.env.NEXT_APP_SANITY_TOKEN
});
const builder = imageUrlBuilder(client);
export const urlFor = (source) => builder.image(source);
I'm following a tutorial on NextJS tutorial on youtube. I was expecting it to be run smoothly, but didn't work
So I have the same issue with you. So make sure your enviroment variables starts with VITE in case you are using VITE
In my case , I did with this way
import SanityClient from "#sanity/client"
import imageUrlBuilder from "#sanity/image-url";
// take these from sanity manage
export const client = new SanityClient({
projectId:import.meta.env.VITE_REACT_APP_SANITY_PROJECT_ID,
dataset:'production',
apiVersion:'2023-01-10',
useCdn:true,
token:import.meta.env.VITE_REACT_APP_SANITY_TOKEN,
})
const builder = imageUrlBuilder(client);
export const urlFor = (source : any) => builder.image(source);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
And my .env file is like this
VITE_REACT_APP_SANITY_PROJECT_ID = aweqfrstbsrgvsrtbvr
VITE_REACT_APP_SANITY_TOKEN = skm29cF1q1VsOgKIFty8D53j2dJKly9Fa..........
Make sure give a space in env file before and after the = sign

Adminjs ComponentLoader not found

I have been trying to make custom component in Adminjs 6.6.5 dashboard but Adminjs ComponentLoader not found error occurs. then i have tried to
import AdminJS from 'adminjs'
const {ComponentLoader} = AdminJS
but i get: Trying to bundle file 'file:/Users/Josip/WebstormProjects/ferry-backend/components/dashboard.jsx' but it doesn't exist
I would really appreciate help...
admin/index.js
import {ComponentLoader} from "adminjs";
const componentLoader = new ComponentLoader()
const Components = {
MyDashboard: componentLoader.override('Dashboard','../components/dashboard.jsx')
}
export { componentLoader, Components }
index.js
import {componentLoader, Components} from "./admin/index.js";
AdminJS.registerAdapter(AdminJSSequelize)
const admin = new AdminJS({
databases: [],
rootPath: '/admin',
resources:[UsersResources, GuestResources, SalesResources, FinancesResources],
components:{
edit: Components.MyDashboard
},
componentLoader
})
you are fixed this problem? I also ran into this problem and don't understand how to solve it
i fixed this problem. You need to do the import as follows
import AdminJs from 'adminjs';
// And now you can use any adminjs dependencies as follows
AdminJs.ValidationError(errors)
My usage example:
if(Object.keys(errors).length) {throw new AdminJs.ValidationError(errors)} else {...}
Good luck with your development!

Firebase getAuth() throws error getProvider of undefined but can access database

I have the following code running on a Node server.
import admin from 'firebase-admin';
import {getAuth} from 'firebase/auth';
class MyFirebase {
constructor() {
console.log("MyFirebase Constructor");
this.firebaseApp = admin.initializeApp({
credential: admin.credential.cert("PATH_TO_CERT/cert.json"),
databaseURL: "https://DATABASE_URL",
});
console.log("App name="+firebaseApp.name);
this.defaultAuth = getAuth(firebaseApp);
this.database = this.firebaseApp.database();
// database ref code here...
}
}
and it throws the following error:
return app.container.getProvider(name);
TypeError: Cannot read property 'getProvider' of undefined
If I remove "firebaseApp" from the getAuth(..) call I get this error:
No Firebase app '[DEFAULT'] has been created - call Firebase
App.initializeApp() (app/no-app)
However the "console.log("App Name...")" line produces:
App name=[DEFAULT]
So clearly a DEFAULT app has been created. Additionally if I remove the "getAuth..." call the database calls pulling data from the realtime database below it work just fine, which seem to imply the authentication worked properly because I can access data from the database.
What the heck is going on?
You are confusing Firebase Admin SDK (Node.js) with Firebase Javascript SDK. The former is for the back-end, while the latter is for the front-end. I understand your confusion because the front-end package/s are installable via NPM, although they are meant to be bundled with front-end code.
You can't do this:
import admin from 'firebase-admin' // back-end code
import { getAuth } from 'firebase/auth' // front-end code !!!
const adminApp = admin.initializeApp(...)
getAuth(adminApp) // TypeScript actually catches this error
/*
Argument of type 'App' is not assignable to parameter of type 'FirebaseApp'.
Property 'automaticDataCollectionEnabled' is missing in type 'App' but required in type 'FirebaseApp'.ts(2345)
app-public.d.ts(92, 5): 'automaticDataCollectionEnabled' is declared here.
const adminApp: admin.app.App
*/
If you are on the back-end, just use adminApp.auth() to get the Auth instance. If on the front-end, you need to call getAuth with the front-end Firebase App instance:
import { initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
const app = initializeApp(...)
const auth = getAuth(app)
The new modular apis have a slightly different syntax. The following should still work if you wrap it in a class, but as long as you only do this once at the top of your express? server you shouldn't need to use a class.
Also, I'm using the require syntax but imports should work too depending on your setup.
//Import each function from the correct module.
const { initializeApp, applicationDefault } = require("firebase-admin/app");
const { getAuth } = require("firebase-admin/auth");
const { getDatabase } = require("firebase-admin/database");
const app = initializeApp({
credential: applicationDefault(), //Don't forget to export your configuration json https://firebase.google.com/docs/admin/setup
databaseURL: "https://DATABASE_URL",
});
const auth = getAuth(app)
const database = getDatabase(app)
It's not super well documented but you can find hints in the Admin SDK reference: https://firebase.google.com/docs/reference/admin/node/firebase-admin.auth
One tip: In VSCode you should see the a description of each function when you hover over them, if you have the import path formatted correctly.

App Object in Electron Module and getAppPath throws Error

I have a strange problem with my application. I get an error, and I can't solve it. First at all, I installed a new project, so everything is clean. Someone sent me this repo to use for an Angular, Electron and Nodejs Application. Everything worked fine, but then I decided to install an embedded database like sqlite3. For this I found NeDB, and the module is perfect for my needs. First I had the problem, has nothing to do with my general problem, that I can't create a database file. So I read that I can only create files in my application path, because something about Electron and that's working in a browser.
I found the getAppPath() method that is implemented in my app object from the Electron module. Here starts the problem. For hours I tried to get the application path from this object. Finally, I wrote this code.
import { Injectable } from '#angular/core';
var nedb = require('nedb');
import { app } from 'electron';
import * as path from 'path';
#Injectable()
export class DatabaseService {
app: typeof app;
Database: any;
constructor() {
this.app = window.require("electron").app;
this.Database = new nedb({ filename: path.join(this.app.getAppPath(), '/diary.db'), autoload: true, timestampData: true });
var scott = {
name: 'Scott',
twitter: '#ScottWRobinson'
};
this.Database.insert(scott, function(err, doc) {
console.log('Inserted', doc.name, 'with ID', doc._id);
});
}
}
And I get this error.
I found this posting, but I don't really understand what the post is trying to tell me. I followed the links, but nothing seems to help. Anyone have an idea?

Placing Backbone Models in external files using node.js

I'm trying to find my way through node.js and backbone.js. My intention is to share at least all model-states with the server and browser. Right now I'm not quite sure if I really need to share views as well. I also want to handle all routes by express and nodejs and not backbone. To keep my code a wee bit more structured I was looking forward to keep each model in a separate *.js file. By doing so I'm running into following error message:
TypeError: Object #<Object> has no method 'extend'
I thought it might be a problem with underscore missing in the separate file, so here is my basemodel:
models/BaseModel.js
var Backbone = require('../node_modules/backbone'),
_ = require('../node_modules/underscore'),
var BaseModel = Backbone.Model.extend({
modelName: 'basemodel'
});
exports.BaseModel = BaseModel;
app.js
var BaseModel = require('./models/BaseModel');
var MyModel = BaseModel.extend({
// ... attributes, functions etc.
});
Does anyone have a hint what I'm doing wrong there?
Then try this code in app.js:
BaseModel = require('./models/BaseModel').BaseModel;
Or in models/BaseModel.js not of exports.BaseModel = BaseModel; use it - module.exports = BaseModel
I actually figured it out. The flaw was in referencing to the BaseModel, so
this
var MyModel = BaseModel.extend({
//
});
had to turn into:
var MyModel = BaseModel.BaseModel.extend({
//
};
because of
exports.BaseModel = BaseModel;
in BaseModel.js

Resources