how to connect sqlite3 with electron js - node.js

please guide me through a full process, that I connect my electron app with sqlite3.
because I have a lot of issues occurring in my electron js.
Thank you.
Main.js:
const{app,BrowserWindow,ipcMain}=require("electron");
app.on("ready",createWindow);
const si = require("systeminformation");
require("electron-reload")(__dirname);
function createWindow()
{
const window = new BrowserWindow({
width: 800,
height:600,
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
}
});
window.webContents.openDevTools();
window.loadFile(__dirname+ "/index.html");
}
ipcMain.on("get-cpu-usage",(events,args)=>{
console.log(args);
});
renderer.js:
const{ipcRender} = require("electron")
const os=require("os");
const cpuName=document.getElementById("cpu-name");
const cpuCores =document.getElementById("cores");
const cpuUsage =document.getElementById("cpu-usage");
const cpus=os.cpus();
cpuName.innerText=`CPU: ${cpus[0].model}`;
cpuCores,innerText=`Cores Available: ${cpus.length}`;
setInterval(() =>{
console.log("sending message to get cpu stats")
ipcRender.send("get-cpu-usage", "Hello sheraz The render process")
},2000)

By far the easiest way to use SQLite with electron is with electron-builder.
First, add a postinstall step in your package.json:
"scripts": {
"postinstall": "install-app-deps"
...
}
and then install the necessary dependencies and build:
npm install --save-dev electron-builder
npm install --save sqlite3
npm run postinstall
electron-builder will build the native module for your platform, with the correct name for the Electron binding; and you can then require it in code as normal.

Related

Can't resolve 'http' in '/tmp/build_6c942c65/src' in Heroku: App works locally

My app which works locally cannot be pushed to heroku because of this error message:
Module not found: Error: Can't resolve 'http' in '/tmp/build_6c942c65/src'
Steps I have tried:
Downgrading react scripts to 4.0.2
Trying install http-browserify https-browserify and updating next.config.js to the below:
module.exports = {
webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
config.resolve.alias.https = "https-browserify";
config.resolve.alias.http = "http-browserify";
return config;
},
};
Installing node-polyfill-webpack-plugin, creating a webpack.config.js and adding
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
module.exports = {
// Other rules...
plugins: [
new NodePolyfillPlugin()
]
};
Also
putting this in webpack.config.js
module.exports = {
target: "node",
}
Can anyone help.
App directory looks like this:
Can anyone help?
Thanks

Firebase - TypeError: Path must be a string. Received undefined

I am just starting up with firebase.
i am not sure ins and out of the firebase and based on my vaguely understanding, I have configured my app this way.
In the main Index.js file, I am requiring
const path = require('path')
const firebaseConfig = require("./src/config/firebaseConfig.js")
const firebaseDb = require("./src/helperFunctions/firebase_db.js")
Here, firebaseConfig is the place where I am configuring my firebase
const firebaseConfigJSON = require("./functions-config.json")
const admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.cert(firebaseConfigJSON),
databaseURL: "https://functions-firebase-43a59.firebaseio.com"
})
const db = admin.firestore()
db.settings({ timestampsInSnapshots: true });
module.exports = {
db
}
and then using this imported Db in firebaseDb
//All the operations at firebase store would be done from here
const firebaseDb = require("./../config/firebaseConfig.js")
firebaseDb.db.collection('users').add({
name: "Rohit Bhatia",
age: "24"
})
.then((response) => {
console.log("this is response", response)
})
.catch((err) => {
console.log("This is error in firebase", err)
})
Since most of the code is singleton here, I was expecting everything to go smoothly until I received following error
This is error in firebase TypeError: Path must be a string. Received
undefined
at assertPath (path.js:28:11)
at Object.join (path.js:1236:7)
at getPath (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/dir-glob/index.js:6:41)
at globs.concat.map.x (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/dir-glob/index.js:47:59)
at Array.map ()
at module.exports.sync (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/dir-glob/index.js:47:33)
at globDirs (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/globby/index.js:58:9)
at getPattern (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/globby/index.js:61:64)
at globTasks.reduce (/Users/anilbhatia/Desktop/google-functions/functions/node_modules/globby/index.js:107:19)
at Array.reduce ()
Can someone please help me in figuring out what could I be doing wrong? or perhaps did I actually got the firebase?
My initial goal was to create a collection in my firebase via my express app before putting data from api routes.
Try running:
npm install firebase-admin#6.4.0
Also you can do:
npm install
npm run build (inside functions folder.)
Then firebase deploy.
Fixed it for me.
We were able to revert the dir-glob to 2.0.0 by adding:
"dir-glob": "2.0.0",
"globby": "8.0.0",
In the package.json dependencies.
You can do this with:
npm install dir-glob#2.0.0 --save
npm install globby#8.0.0 --save
We then deleted the node_modules and run: npm install and deployed to Firebase
Future googler's
Make sure in your firebase.json file you have the correct source path:
{
"functions": {
"predeploy": "npm run build",
"source": "."
}
}

How create a module with asynchronous exports in NodeJS with ES6

I want to create a module (install in node_modules) for my projects which call the same API. But when I export my async function I get an error :
index.js Unexpected token (3:21)
You may need an appropriate loader to handle this file type.
Index.js is my module file.
Here's example code:
export default async function({path, method = 'GET', body}, userToken = null, contentType = 'application/json') {
// some code here ...
}
And in my project I import like this :
import invokeApi from 'my_sdk';
It seems that there is an issue with your build configuration on the consumer code side. You must enable async/await when consuming async APIs as it requires regeneration runtime (or install Node 7.6 or later as it brings native async/await support).
If you use this code on the web you might probably need to import 'babel-polyfill' in the entry point file (probably main.js, app.js or index.js) and set up Webpack to use Babel to transpile your code.
Works like a charm using babel-node with following "presets": ["es2015", "stage-0"]:
asyncModule.js
const sleep = async duration =>
new Promise(resolve => setTimeout(resolve, duration))
export default async function({path, method = 'GET', body}, userToken = null, contentType = 'application/json') {
await sleep(500)
return "Hello :)"
}
index.js
import asyncExample from './asyncModule'
const main = async () => {
const result = await asyncExample({path: '/', body: ''});
console.log(result)
main();
npm start
"start": "babel-node --presets es2015 index.js"

Bundle error using webpack for Electron application `Cannot resolve module 'electron'`

I am trying to create an Electron application with React. I use Webpack to compile the React JSX syntax, but when I try to compile with webpack command, I got this error:
ERROR in ./app.jsx
Module not found: Error: Cannot resolve module 'electron' in /Users/masterT/Downloads/gist
# ./app.jsx 6:18-37
Here is the application code.
I am doing something wrong?
A very simple solution :
const remote = window.require('electron').remote;
webpack will ignore this require
Webpack tries to resolve electron module with the installed node_modules. But the electron module is resolved in Electron itself at runtime. So, you have to exclude particular module from webpack bundling like this:
webpack.config.js:
module.exports = {
entry: './app.jsx',
output: {
path: './built',
filename: 'app.js'
},
target: 'atom',
module: {
loaders: [
{
loader: 'babel',
test: /\.jsx$/,
query: {
presets: ['es2015', 'react']
}
}
]
},
externals: [
(function () {
var IGNORES = [
'electron'
];
return function (context, request, callback) {
if (IGNORES.indexOf(request) >= 0) {
return callback(null, "require('" + request + "')");
}
return callback();
};
})()
]
};
You can set target: 'electron' in your webpack config and then you don't have to exclude electron in externals.
From webpack documentation:
"electron" Compile for usage in Electron – supports require-ing Electron-specific modules.
I tried most of the above examples, but none of them seemed to work for me.
I then installed Electron using npm and then used yarn build
It worked and I got my production build.
npm i electron
Also, webpack.config.js:
const nodeExternals = require('webpack-node-externals')
module.exports = {
...
externals: [ nodeExternals(), 'react', 'electron' ],
...
}
Your package.json has 'electron-prebuilt' but you require 'electron' in your code. Have you tried require-ing 'electron-prebuild'?

Update NPM modules from within grunt

I'm trying to automate the update of new node modules but, npm update seems not to want to run correctly from within grunt also updating the package.json file with the new version. I want to do this regardless of what version is specified in the package.json file.
What I found till now is the node module: npm-check-updates (https://www.npmjs.com/package/npm-check-updates)
The problem is that I can't get it to work with other modules like npm-shell or npm-exec.
I've tried using npm update -D directly, but that fails too.
I'm asking if it can be done.
Here's what I use:
grunt.registerTask('update', 'Update npm modules', function() {
var exec = require('child_process').exec;
var cb = this.async();
exec('npm update -D', {}, function(err, stdout) {
console.log(stdout);
cb();
});
});
If i'm correct you're trying to update ALL of your npm packages inside of your package.json file? I would recommend using this package.
Install the package.
npm install grunt-auto-install --save-dev
Add it to your grunt tasks.
grunt.loadNpmTasks('grunt-auto-install');
Then add the configuration to your gruntfile.js
grunt.initConfig({
auto_install: {
local: {},
subdir: {
options: {
cwd: 'subdir',
stdout: true,
stderr: true,
failOnError: true,
npm: '--production'
}
}
},
});
Here is the reference:
https://www.npmjs.com/package/grunt-auto-install
AFTER YOUVE UPDATED THE PACKAGES
Update your devDependencies and dependencies automatically with a grunt task.
Install the npm module to update your packages in your dev dependencies object.
npm install --save-dev grunt-dev-update
Add it to your grunt tasks.
grunt.loadNpmTasks('grunt-dev-update');
Add your configuration to your gruntfile.
devUpdate: {
main: {
options: {
//task options go here
}
}
}
Reference:
https://www.npmjs.com/package/grunt-dev-update
I found a solution using npm-check-update (ncu) and grunt.util.spawn:
// Install NPM Updates
grunt.registerTask('update-npm', 'Update package.json and update npm modules', function() {
grunt.log.writeln('If you get an error here, run "npm install -g npm-check-updates".');
grunt.task.run('npm-write-new');
grunt.task.run('npm-update');
});
// Check for npm module updates
grunt.registerTask('npm-check', 'Check for npm modules updates', function() {
var done = this.async();
grunt.log.writeln('Checking for npm modules updates ...');
grunt.util.spawn({
cmd: 'ncu',
args: '',
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('No files were modified.');
done();
});
});
// Write new versions to packages.json
grunt.registerTask('npm-write-new', 'Write new versions to package.json', function() {
var done = this.async();
grunt.log.writeln('Checking for npm modules updates ...');
grunt.util.spawn({
cmd: 'ncu',
args: ['-u'],
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('New versions were written to "package.json".');
done();
});
});
// Update npm modules
grunt.registerTask('npm-update', 'Update npm modules', function() {
var done = this.async();
grunt.log.writeln('Installing npm modules updates ...');
grunt.util.spawn({
cmd: 'npm',
args: ['update','--loglevel','warn'],
opts: {
stdio: 'inherit',
}
}, function () {
grunt.log.writeln('NPM modules were updated.');
done();
});
});

Resources