I tried to do serial port to listen my COMports with electron-vue.js.
When I try to code this below.
const SerialPort = require("serialport");
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort("COM3", {
baudRate: 9600,
});
const parser = new Readline();
port.pipe(parser);
//Read Data
parser.on("data", (line) => {
console.log(line);
});
//Send Data
parser.write("Sended Data !");
I got this below error in console.
TypeError: Cannot read property 'modules' of undefined
at Object.eval (bindings.js?dfc1:29)
at eval (bindings.js:223)
at Object../node_modules/bindings/bindings.js (0.js:231)
at webpack_require (app.js:854)
at fn (app.js:151)
at eval (linux.js?88eb:2)
at Object../node_modules/#serialport/bindings/lib/linux.js (0.js:65)
at webpack_require (app.js:854)
at fn (app.js:151)
at Object.eval (index.js?c888:14)
How can I solve this problem ?
By the way, When I try to run this code in node.js, it runs. But when I try to run this code in Vue.js, it did not run.
Thanks
serialport uses physical resource so can't be webpacked as client package. you need to mark serialport as external for the builder.
// vue.config.js
module.exports = {
pluginOptions: {
electronBuilder: {
externals: ["serialport"],
},
},
},
Related
I want to know why this custom module is not working
module:
var mariadb = require('mariadb');
class DB{
constructor(){
this.db_conn = null;
this.db_pool = mariadb.createPool({
host:"localhost",
user:"root",
password:"",
database:"testdatabse"
});
this.db_pool.getConnection().then(conn => {
this.db_conn = conn;
});
}
};
module.exports = function(){
return (new DB()).db_conn;
}
but the same code working in main javascript file
main file here:
var http = require('http');
var url = require('url');
var mariadb = require('mariadb');
var dbs = require('./modules/mariadb-connector'); //here i am importing the module
var db_conn;
var db = mariadb.createPool({
host:"localhost",
user:"root",
password:"",
database:"testdatabase"
});
db.getConnection().then(conn => {
db_conn = conn;
});
console.log(dbs.query("SELECT * FROM array_languages")); //here it's throwing error
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
console.log(req.url);
db_conn.query("SELECT * FROM array_languages").then(data => {
res.write(JSON.stringify(data));
res.end();
});
}).listen(8080,"localhost");
error:
PS D:\Programs\nodejs\test> node index.js
D:\Programs\nodejs\test\index.js:16
console.log(dbs.query("SELECT * FROM array_languages"));
^
TypeError: dbs.query is not a function
at Object.<anonymous> (D:\Programs\nodejs\test\index.js:16:17)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
here the error when I tried to use this module
at console.log(dbs.query("SELECT * FROM array_languages"));
please explain why is working in main js file but not in module.
is there any way to achieve this
var dbs = require('./modules/mariadb-connector')
sets dbs to the exports object of the custom module, which is a function to return a connector to a new db:
function(){
return (new DB()).db_conn;
}
You could try calling the exports module when setting dbs like
var dbs = require('./modules/mariadb-connector')();
However, this leave the problem that the .db_conn property of new DB() is set asynchronously in a promise callback. Immediately after requiring the module db-conn in the module will still be null.
Some form of asynchronous processing needs to be implemented, taking into consideration that at the moment there is a race condition between getting the database connection and servicing a request to look up the database. At the moment setting up the connection wins the race: this is the only reason it appears to work when the connection code is in the main module.
An Outline of asynchronous processing for ideas:
var http = require('http');
var url = require('url');
var mariadb = require('mariadb');
async function db_conn() {
let db_pool = mariadb.createPool({
host:"localhost",
user:"root",
password:"",
database:"testdatabse"
});
const conn = await db_pool.getConnection();
return conn;
}
db_conn().then( db_conn => {
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'application/json'});
console.log(req.url);
db_conn.query("SELECT * FROM array_languages").then(data => {
res.write(JSON.stringify(data));
res.end();
});
}).listen(8080,"localhost");
})
.catch( err=> {
console.error( err));
process.exit(1);
});
Well, it's not the same code, is it? Your problem is here:
this.db_pool.getConnection().then(conn => {
this.db_conn = conn;
});
This is an async function. It will finish running after the constructor has run. You're importing return (new DB()).db_conn when db_conn is null.
If you're set on using it as a class, I'd create a method getConnection that got the value from db_conn after it has finished running, and import the instance instead of the the property
I am developing in vuejs, focused on IPTV service. The problem I am having is that when I want to do the following
const {channels} = require('../lib/utils/index.js');
in the file actions.js it shows me the following error
index.js?c45a:26 Uncaught TypeError: fs.readFileSync is not a function
at Module.eval (index.js?c45a:26)
at eval (index.js:64)
at Module../src/lib/utils/index.js (app.js:958)
at __webpack_require__ (app.js:786)
at fn (app.js:151)
at eval (actions.js?63e0:2)
at Module../src/store/actions.js (app.js:1005)
at __webpack_require__ (app.js:786)
at fn (app.js:151)
at eval (index.js?4360:1)
Is there any way to solve this problem?
../lib/utils/index.js
const fs = require('fs');
const fetch = require('node-fetch');
const parser = require('iptv-playlist-parser');
const USM3U = require('./urls/us.m3u');
/***
* #async
* #method GM3U
* #param {empty}
* #Summary Generate US m3u file
* #Description THIS FUNCTION SHOULD NOT BE USED.
***/
const GM3U = async() =>{
const res = await fetch(`${USM3U}`);
const data = await res.text();
fs.writeFile('us.m3u' , data , (err) =>{
if(err){
console.log(err);
}else{
console.log('The file us.m3u was saved!');
}
})
};
const usPlaylist = fs.readFileSync('us.m3u' , {encoding: 'utf8'});
const channels = parser.parse(usPlaylist);
module.exports = {
channels
};
actions.js
When I try to make the import I get the error Uncaught TypeError: fs.readFileSync is not a function
const {channels} = require('../lib/utils/index.js');
You can't use fs package with Vue.js framework .Because fs is not frontend technology . Instead of that try to use AJAX call to solve your issue .
my init.js file
var web3 = require('web3');
fs = require('fs');
solc = require('solc');
web3 = new web3(new web3.providers.HttpProvider("http://localhost:8545"));
code = fs.readFileSync('kyc.sol').toString();
//contract = web3.eth.compile.solidity(code);
contract = solc.compile(code);
function after2Delay() {
contractInstance = kycContract.at(deployedContract.address);
console.log(contractInstance.address);
}
function afterDelay() {
abiDefinition = JSON.parse(contract.contracts[':kyc'].interface);
byteCode = contract.contracts[':kyc'].bytecode;
kycContract = web3.eth.contract(abiDefinition);
deployedContract = kycContract.new({data: byteCode, from: web3.eth.accounts[0], gas: 4700000});
setTimeout(after2Delay, 3000);
}
setTimeout(afterDelay, 8000);
After I run rpc using ganache-cli . I run the above code using node init.js . I'm getting following error
(function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath"normalize";var ret=nodeFS["readFileSy
TypeError: Cannot read property 'interface' of undefined
at Timeout.afterDelay [as _onTimeout] (/Users/pc/Documents/Programs/KYC-chain-master/root/init.js:16:59)
at ontimeout (timers.js:458:11)
at tryOnTimeout (timers.js:296:5)
at Timer.listOnTimeout (timers.js:259:5)
I've read it from here that the problem could be solved my making contract name same as file name. My contract name and file name are same i.e kyc
How to resolve this issue ?
I correctly installed ffmpeg I'm able to check it by writing ffmpeg in cmd which give me this result
Now in my electron app in my index.html I'm geting input from user and sending custom event to electron side of app which lays in index.js entry point
index.html
<script>
const electron = require('electron');
const { ipcRenderer } = electron;
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
const { path } = document.querySelector('input').files[0];
ipcRenderer.send('video:submit', path);
});
</script>
and using ffmpeg.ffprobe I'm trying to get metadata of video updated to input in electron side like so:
const electron = require('electron');
const ffmpeg = require('fluent-ffmpeg');
const { app, BrowserWindow, ipcMain } = electron;
app.on('ready', () => {
const mainWindow = new BrowserWindow({});
mainWindow.loadURL(`file://${__dirname}/index.html`);
});
ipcMain.on('video:submit', (event, path) => {
ffmpeg.ffprobe(path, (err, metadata) => {
console.log(metadata);
//console.log(metadata.format.duration);
});
});
And it console that metadata is undefined, when I uncomment console.log(metadata.format.duration) it says
typeError: cannot read property
'format' of undefined
What I'm doing wrong?
So I set two new environment variables and now other error occure when I console.log(error):
{ Error: spawn C:\Users\Borys\Documents\videoinfo\ffmpeg\bin ENOENT
at exports._errnoException (util.js:1024:11)
at Process.ChildProcess._handle.onexit (internal/child_process.js:192:19)
at onErrorNT (internal/child_process.js:374:16)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
code: 'ENOENT',
errno: 'ENOENT',
syscall: 'spawn C:\\Users\\Borys\\Documents\\videoinfo\\ffmpeg\\bin',
path: 'C:\\Users\\Borys\\Documents\\videoinfo\\ffmpeg\\bin',
spawnargs:
[ '-show_streams',
'-show_format',
'C:\\Users\\Borys\\Documents\\portfolio\\img\\header_video.mp4' ] }`
( I had to paste it as code because it was saying that my post containt code that is not properly formatted)
Alright thanks to #Alexander Leithner and this question I figured it out. So error was my environment variables which should be:
FFMPEG_PATH with value of path to ffmeg.exe
FFPROBE_PATH with value of path to ffprobe.exe
PATH with value of C:.......\ffmpeg\bin
I'm trying to get node-serialport to work with electron and webpack.
I'm importing serialports as external module:
# webpack.config.js
externals: {
serialport: "serialport"
}
This is the code in my app:
// read NMEA data from serial port
const SerialPort = require('serialport');
console.log(SerialPort.list());
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort('/dev/tty.Redmi-ShareGPS', { baudRate: 4800 });
const parser = port.pipe(new Readline({ delimiter: '\r\n' }));
// Open errors will be emitted as an error event
port.on('error', function(err) {
console.log(err.message);
})
// send NMEA data to GPS.js
parser.on('data', function(data) {
// gps.update(data);
});
Trouble is in first line: const SerialPort = require('serialport');
Webpack compiles everything without error, but I have a browser console error:
Uncaught ReferenceError: serialport is not defined
at Object.<anonymous> (bundle.js:65651)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:65630)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:31520)
at __webpack_require__ (bundle.js:20)
at Object.<anonymous> (bundle.js:25595)
at __webpack_require__ (bundle.js:20)
at _ol_ (bundle.js:63)
at bundle.js:66
Which origins at this in webpack generated bundle.js:
/* 315 */
/***/ (function(module, exports, __webpack_require__) {
// read NMEA data from serial port
const SerialPort = __webpack_require__(316);
console.log(serialport.list());
const Readline = SerialPort.parsers.Readline;
const port = new SerialPort('/dev/tty.Redmi-ShareGPS', { baudRate: 4800 });
const parser = port.pipe(new Readline({ delimiter: '\r\n' }));
// Open errors will be emitted as an error event
port.on('error', function (err) {
console.log(err.message);
});
// send NMEA data to GPS.js
parser.on('data', function (data) {
// gps.update(data);
});
/***/ }),
/* 316 */
/***/ (function(module, exports) {
module.exports = serialport;
/***/ })
/******/ ]);
The error line is exactly module.exports = serialport;
According to webpack docs on externals, I suppose I somehow need to include serialport as a global variable, but the example is for jQuery which is a js file, and serialport is node module.
How to make it work?
After many hours of frustration, I moved
const SerialPort = require('serialport');
from javascript file which is supposed to be bundled by webpack to index.html:
<script>
const SerialPort = require('serialport');
</script>
<script src="dist/bundle.js"></script>
SerialPort is now recognized.
Also, it seems like webpack-dev-server doesn't work very well with Electron and serialport. I have to launch full electron app.
Try remote.
You might also want to try using remote:
const SerialPort = require( "electron" ).remote.require( "serialport" );
use eval
const serialport = eval(`require('serialport')`)