I am new to Feathers and this could be the most dumb question I have ever asked in my entire life of developer, but I will jump in... hoping you can help me
This extract is from the quick start of Feathers website
<script src="//unpkg.com/#feathersjs/client#^4.3.0/dist/feathers.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<script type="text/javascript">
// Set up socket.io
const socket = io("http://localhost:3030");
const app = feathers();
// Register socket.io to talk to the server
app.configure(feathers.socketio(socket));
// Form submission handler that sends a new message
async function sendMessage() {
const messageInput = document.getElementById("message-text");
// Create a new message with the input field value
await app.service("messages").create({
text: messageInput.value,
});
messageInput.value = "";
}
// Renders a single message on the page
function addMessage(message) {
document.getElementById("main").innerHTML += `<p>${message.text}</p>`;
}
const main = async () => {
// Find all existing messages
const messages = await app.service("messages").find();
// Add existing messages to the list
messages.forEach(addMessage);
// Add any newly created message to the list in real-time
app.service("messages").on("created", addMessage);
};
main();
</script>
And I am wondering:
Where the functions io() from const socket = io("http://localhost:3030");and feathers() from const app = feathers(); are defined ? That doesn't make an error
those two functions are defined inside
<script src="//unpkg.com/#feathersjs/client#^4.3.0/dist/feathers.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
if you want to use them inside webpack project (react, vue, ...) use proper packages:
const feathers = require('#feathersjs/feathers');
const socketio = require('#feathersjs/socketio-client');
const io = require('socket.io-client');
const socket = io('http://api.feathersjs.com');
const app = feathers();
Related
The goal is to call a function from my main script that connects to a database, reads a document from it, stores pieces of that document in a new object, and returns that object to my main script. The problem is I cannot get it all to work together. If I try one thing, I get the results but my program locks up. If I try something else I get undefined results.
Long story short, how do I open a database and retrieve something from it to another script.
The program is a quiz site and I want to return the quiz name and the questions.
const myDb = require('./app.js');
var myData = myDb.fun((myData) => {
console.log(myData.quizName);
});
Here is the script that tries to open the database and find the data
const { MongoClient } = require("mongodb");
const {mongoClient} = require("mongodb");
const uri = connection uri goes here but my name is hard coded into it at the moment so I removed for privacy
const client = new MongoClient(uri);
const fun = async (cback) => {
try {
await client.connect();
const database = client.db('Quiz-Capstone');
const quizzes = database.collection('Quiz');
const query = {quizName: "CIS01"};
const options = {
sort: {},
projection: {}
};
const quiz = await quizzes.findOne(query, options);
var quizObject = {
quizName: quiz.quizName,
quizQuestions: quiz.quizQuestions
}
//console.log(testOb);
} finally {
await client.close();
cback(quizObject);
}
}
fun().catch(console.dir);
module.exports = {
fun: fun
}
UPDATE: Still stuck. I have read several different threads here about asynchronous calls and callbacks but I cannot get my function located in one file to return a value to the caller located in another file.
I am trying to fetch events from azure eventhub using a timer triggered azure function. I am able to fetch the events successfully with a simple nodejs code while running in my machine locally. But if the same code if i execute through a node js azure function, it doesn't work. I get the below error message. Is there something I am missing ?
TypeError: EventHubConsumerClient is not a constructor' Stack: TypeError: EventHubConsumerClient is not a constructor at Object.<anonymous>
Below is the sample code
const { ContainerClient } = require("#azure/storage-blob");
const { BlobCheckpointStore } = require("#azure/eventhubs-checkpointstore-blob");
const connectionString = "Endpoint=xxxx";
const eventHubName = "yyyy";
const consumerGroup = "default";
const storageConnectionString = "abcd";
const containerName = "eventhubcontainer";
module.exports = async function (context, myTimer) {
const containerClient = new ContainerClient(storageConnectionString, containerName);
const checkpointStore = new BlobCheckpointStore(containerClient);
const consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName, checkpointStore);
}
Please help
You are missing this line.
const { EventHubConsumerClient } = require("#azure/event-hubs");
You just need to pass consumerGroup and the ConnectionString to the EventHubConsumerClient constructor
const consumerClient = new EventHubConsumerClient(this.consumerGroup, eventHubConnectionString);
Here is an Example
im trying to export a var to another file in a nodejs application, i ve managed to export it, but the result of the variable should change when a user logs in, does the export notice the change and export it again? If not how can i do it?
File im trying to export from, the arrow line is the var itself
var express = require('express');
var router = express.Router();
var url = require('url');
var userinfo ="aaa";
// User Api
router.get('/user/:userid', check_token, (req, res) => {
var userid = req.params.userid;
users.getById(userid)
.then(data => {
console.log(data)
userinfo=data; <--------------------------------------------------------------------
res.jsonp(data);
})
.catch(err => {
res.status(500).jsonp(err);
});
})
var routeinfo;
module.exports= {routeinfo : router,
userinfo: userinfo}
file im tryng to export to
var use_test=require('../routes/api')
var userf = require('../routes/api').userinfo;
var socket_io = require('socket.io');
var io = socket_io();
var socketio = {};
socketio.io = io;
var users = [];
io.on('connection', function(socket){
console.log('A user connected');
console.log(`Socket connected ${socket.id}`)
console.log(`User -> ${userf}`)
});
module.exports = socketio;
The way you are doing this is pretty unconventional to say the least.
The correct way making a middleware and use it for the userinfo, which is the standard way.
Some problems with this approach is, Your socket.io is dependant upon the user(or any auto ajax call) hitting the user/:userid route so for multiple user hitting the route, the userinfo will not be contained for that particular session. One user's userinfo will be shown for another user.
Think it in terms of session, a simplistic way would be using an object to hold the value in userid: userInfo format.
For the original problem, I think as you are using var userinfo ="aaa"; a string, it is not changing the pointer.
Maybe, using a object you can use the data as it will be pointers.
const userinfo = {
data: null
}
and then,
userinfo.data = data;
But I won't go into the details as this is not a good way to achieve what you are trying to achieve.
I am trying to understand the following code taken from a service created in a feathersjs app.
// Initializes the `users` service on path `/users`
const createService = require('feathers-knex');
const createModel = require('../../models/users.model');
const hooks = require('./users.hooks');
const filters = require('./users.filters');
module.exports = function () {
const app = this;
const Model = createModel(app);
const paginate = app.get('paginate');
const options = {
name: 'users',
Model,
paginate
};
// Initialize our service with any options it requires
app.use('/users', createService(options));
// Get our initialized service so that we can register hooks and filters
const service = app.service('users');
service.hooks(hooks);
if (service.filter) {
service.filter(filters);
}
};
This file is then imported as follows:
// many requires..
const feathers = require('feathers');
// more requires
const services = require('./services');
// other requires
const app = feathers();
Can someone explain as to what does the line
const app = this
do in the code that is creating the service?
It assigns the value of this to a variable (well, a constant) with a name that more clearly describes the value than this does. It is designed to make the code easier for maintainers to understand.
What is the best way to manipulate DOM within an electron app?
I made some tutorials from docs using ipc and webcontents with no luck
My app is so simple, I just want to use the web like a console and showing messages (render proc) comming from the results of several sync functions (main proc)
I updated the question with real code.
I'm going to put another code, more simple to see and more simple to test (I think), is real code and works (but not like I want)
When I launch electron only writes the last message.
Ok, the response is really fast and I may not see the first messsage but to discard that I put a setTimeout and a large for() loop too, to make the uppercase function takes longer
index.js
const electron = require('electron');
const {app} = electron;
const {BrowserWindow} = electron;
const ipc = require('electron').ipcMain
app.on('ready', () => {
let win = new BrowserWindow({width: 800, height: 500});
win.loadURL('file://' + __dirname + '/index.html');
// Emitted when the window is closed.
win.on('closed', () => {
win = null;
});
// Event that return the arg in uppercase
ipc.on('uppercase', function (event, arg) {
event.returnValue = arg.toUpperCase()
})
});
index.html
<html>
<body>
<div id="konsole">...</div>
<script>
const ipc = require('electron').ipcRenderer
const konsole = document.getElementById('konsole')
// Functions
let reply, message
// First MSG
reply = ipc.sendSync('uppercase', 'Hi, I'm the first msg')
message = `Uppercase message reply: ${reply}`
document.getElementById('konsole').innerHTML = message
// Second MSG
reply = ipc.sendSync('uppercase', 'Hi, I'm the second msg')
message = `Uppercase message reply: ${reply}`
document.getElementById('konsole').innerHTML = message
</script>
</body>
</html>
You can comminicate between your frond-end and back-end with webContents and IPC. Then, you'll be able to manipulate your codes in front-end with backend's directive.
For Instance (Backend to Frontend);
Your main.js is sending a message to your front-end.
mainwindow.webContents.send('foo', 'do something for me');
Your frond-end will welcome that message here;
const {ipcRenderer} = require('electron');
ipcRenderer.on('foo', (event, data) => {
alert(data); // prints 'do something for me'
});
For Instance (Frontend to Backend);
Your frond-end;
const {ipcRenderer} = require('electron');
ipcRenderer.send('bar',"I did something for you");
Your back-end;
const {ipcMain} = require('electron');
ipcMain.on('bar', (event, arg) => {
console.log(arg) // prints "I did something for you"
event.sender.send('foo', 'done') // You can also send a message like that
})
UPDATE AFTER UPDATING QUESTION;
I tried your codes on my local, It seems like working.
Could you please try it with insertAdjacentHTML instead of 'innerHTML' to just make sure or just use console.log.
Like this;
document.getElementById('konsole').insertAdjacentHTML('beforeend',message);
"result" is a reference type value. "result" always chenge value when result = funcC() or another; Try this:
$('#msg').text(result.ToString());