How can I import a NodeJS variable which comes out of my Arduino into my main web game JavaScript file? - node.js

I am making a web game with threejs, cannonjs, serialport library and arduino with 2 buttons. However when i am trying to import the button press value into my main javascript game file, it sends me into a loop of errors concerning the relative imports of the serial port library.
const { SerialPort } = require('serialport')
const { ReadlineParser } = require('#serialport/parser-readline')
const port = new SerialPort({ path: 'COM11', baudRate: 9600 })
const parser = port.pipe(new ReadlineParser({ delimiter: '\r\n' }))
var eparser = parser.on('data', console.log);
export default eparser;
This is the code to get the button press into the console log.
This is the kinds of errors i run into regarding the serial port library's relative imports
I have tried many other ways like socket.io, johnny five and other such, but have had no luck with finding a solution for my exact problem.

Related

SerialPort NodeJS - SerialPort is not a constructor

Good afternoon, I have a problem with Serial Port ,
I did everything as described in the documentation, but still I get an error SerialPort is not a constructor
const { SerialPort } = require('serialport')
const port = new SerialPort({
path: 'COM4',
baudRate: 9600,
autoOpen: false,
})
Spent several hours solving the problem, tried a lot of things and got to the official documentation, but there was an error here too :)
my nerves left the chat…

Best practices in structuring Node.js & Socket.io app?

Currently I'm developing a node server which uses websockets for communication.
I'm used to applying MVC (or MC) pattern in my apps. I'd like to structure my socket.io in similiar way and my question is how to do this in the best way?
For now I have something like this:
utils/socket.ts:
type IO = null | SocketIO.Server;
let io: IO;
export function init(ioServer: IO) {
io = ioServer;
}
export function getIO(): IO {
return io;
}
app.ts:
import express from 'express';
...
import { init } from './utils/socket';
import startSockets from './controllers';
const app = express();
...
const server = app.listen(process.env.PORT || 5000);
const io = socketio.listen(server);
if (io) {
init(io);
io.on('connect', startSockets);
}
controllers/index.ts:
import { onConnect } from './connect';
import { getIO } from '../utils/socket';
export default function (socket: SocketIO.Socket) {
const io = getIO();
socket.on('connect-player', onConnect);
}
controllers/connect.ts:
import Player from '../models/Player';
export const onConnect = async function (this: SocketIO.Socket, name: string) {
const player = await Player.create({ name });
this.broadcast.emit('player-connected', `Player ${name} joined the game!`);
this.emit(
'player-connected',
`Congratulations ${name}, you successfully joined our game!`,
player,
);
this.on('disconnect', onDisconnect.bind(this, player.id));
};
const onDisconnect = async function (this: SocketIO.Socket, playerId: string) {
const player = await Player.findById(playerId);
await player?.remove();
this.broadcast.emit(
'player-connected',
`Player ${player?.name} left our game!`,
);
};
I'm not sure about using 'this' in my controller and about that singleton pattern in utils/socket.ts. Is that proper? The most important for me is to keep the app clear and extensible.
I'm using express and typescript.
Player.ts is my moongoose schema of player.
I had been struggling with socket.io + express.js a while back, specially I am as well use to apply MVC patterns.
While searching, googling and stack overflowing, these links helped me with the project back than.
https://blueanana.github.io/2017/03/18/Socket-io-Express-4/
https://github.com/onedesign/express-socketio-tutorial
https://gist.github.com/laterbreh/5d7bdf03258152c95b8d
Using socket.io in Express 4 and express-generator's /bin/www
I wont say what is the best way or not, I dont even like that expression. But I will say it is a way, which helped to keep it clear, extensible, organized and very well modularized.
Specially that each project has its own intrinsic requirements and needs.
Hope these can get to help you as well as it did it for me, get the feeling and understanding of how and what it needs to be done on the project.

Nodejs/electron Override chromium browser timeout.

Been looking all over for this information, closest i can see is the
command line switches. i have a web page that i ported to electron and im trying to override the Browser inactivity timeout. for example running a report over 2 minutes the browser times out the connection. My thinking for a quick fix was to wrap in electron and extend the browser timeout.
https://peter.sh/experiments/chromium-command-line-switches/#timeout
https://github.com/electron/electron/blob/master/docs/api/chrome-command-line-switches.md
In Electron the main.js looks to have wrapped the modules in webpack
in all of the examples ive found
it looks like this
You can use app.commandLine.appendSwitch to append them in your app's main script before the ready event of the app module is emitted:
const { app } = require('electron')
app.commandLine.appendSwitch('remote-debugging-port', '8315')
app.commandLine.appendSwitch('host-rules', 'MAP * 127.0.0.1')
app.on('ready', () => {
// Your code here
})
however in my electron file my const app is actually
const path = __webpack_require__(14);
const electron = __webpack_require__(18);
const unusedFilename = __webpack_require__(20);
const pupa = __webpack_require__(23);
const extName = __webpack_require__(24);
const {app, shell} = electron;
i have tried
app.commandLine.appendSwitch("--disable-renderer-backgrounding");
app.commandLine.appendArgument('--disable-timeouts-for-profiling');
Doesnt seem to work, Any hints would be appreciated.

How to use filesystem (fs) in angular-cli with electron-js

I have set up an angular-cli project
(# Angular / cli: 1.0.0-rc.2 node: 6.10.0 os: linux x64)
With electron js (v1.6.2)
And I need to use the filesystem to create / delete .csv files and folders, but I can not do includ in the angular component
How could you configure the angular-cli to be able to: import fs from 'fs'?
You wouldn't configure Angular-CLI to use the NodeJS fs module.
In electron you have 2 processes; main and renderer. The main process controls items such as the browserWindow, which is essentially the 'window' the user sees when they open their app, and in turn this loads the html file for the view. Here, in the main process, you import the fs module.
In the render process, you would handle actions from the view, and send them to the main process. This is where you would use IPC to communicate via events to do something with the main process. Once that event is triggered, the render process takes the event and sends it to main. Main would do something with it, and open a file for example on the desktop.
I would recommend using the electron API demo application to see clear examples of this. Here is an example of print to pdf using FS (from the demo app).
Also, here is an electron application github example written by Ray Villalobos using React, which has some similar concepts that will show you how to integrate components in your app.
Render process:
const ipc = require('electron').ipcRenderer
const printPDFBtn = document.getElementById('print-pdf')
printPDFBtn.addEventListener('click', function (event) {
ipc.send('print-to-pdf')
})
ipc.on('wrote-pdf', function (event, path) {
const message = `Wrote PDF to: ${path}`
document.getElementById('pdf-path').innerHTML = message
})
Main Process:
const fs = require('fs')
const os = require('os')
const path = require('path')
const electron = require('electron')
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
const shell = electron.shell
ipc.on('print-to-pdf', function (event) {
const pdfPath = path.join(os.tmpdir(), 'print.pdf')
const win = BrowserWindow.fromWebContents(event.sender)
// Use default printing options
win.webContents.printToPDF({}, function (error, data) {
if (error) throw error
fs.writeFile(pdfPath, data, function (error) {
if (error) {
throw error
}
shell.openExternal('file://' + pdfPath)
event.sender.send('wrote-pdf', pdfPath)
})
})
})
You can try using const fs = (<any>window).require("fs"); within the component or better still, create a service.ts provider to handle i/o operations.

How to interact with multiple console windows?

how can interact with multiple console windows, from one node.js script?
so far i have researched a bit, and not have found anything that covers my case.
What i want to accomplish is to have one main console window, which it reads my input,
1. action#1
2. action#2
> do 1 // select action
and it would redirect its output to another console window named as Logger which shows the stdout of the action that the user selected, but keeps the main "select action" console window clean.
well i manage to find a way around it, since i wanted to stay with node.js all the way.
start.js
var cp = require("child_process");
cp.exec('start "Logger" cmd /K node logger.js',[],{});
cp.exec("start cmd /K node startAdminInterface.js",[],{});
setTimeout(function(){process.exit(0);},2000);
logger.js
var net = require('net');
net.createServer(function (socket) {
socket.on('data',function(d){
console.log(": "+d.toString("utf8"));
});
socket.on('error',function(err){
console.log("- An error occured : "+err.message);
});
}).listen(9999);
startAdminInterface.js
var net = require("net");
var logger = net.connect(9999);
var readline = require('readline'),
rl = readline.createInterface(process.stdin,process.stdout);
rl.setPrompt('> ');
rl.prompt();
rl.on('line', function(line) {
logger.write(line);
rl.prompt();
}).on('close', function() {
process.exit(0);
});
bottom, line its a workaround not exactly what i was after, put i saw potential, on logger.js it could listen from multiple sources, which is an enormous plus in the application that i'm building.

Resources