Meteor package working on browser but not on server - javascript

There's no problem using the Meteor package strikeout:string.js on the client side (browser JS console), but it throws an error when using it on the server side.
Checked package.js and found api.addFiles('lib/string.js', ['client','server']);, is this not sufficient?
Test code
console.log(S('jon').capitalize().s)
Error on server
ReferenceError: S is not defined

is this not sufficient? YES, you are getting the Reference because you are not requiring it.
In order to use it on the server, you should require it, on this example im using meteorhacks:npm.
It was not possible for me create a Meteorpad of this, so i will do here step-by-step.
First meteor add meteor hacks:npm
Second On the recent create packages.json add this line
{
"string": "3.1.0"
}
Third Now just add the server code.
if (Meteor.isServer) {
Meteor.startup(function () {
var S = Meteor.npmRequire('string'); //server side
console.log(S('jon').capitalize().s)
});
}
Expected Output
I20150326-10:54:05.639(-5)? Jon
Hope it works for you.

Related

back4app cloud code functions problem with ES version

I'm using back4app as backend service to deploy my app, developed in React Native ans JS. I'm testing how to use the 'Cloud Code Functions' of back4app right now...
As I'm a beginner in back4app, I found a problem while using their guide. I'm facing this message error: 'async functions' is only available in ES8 (use 'esversion: 8').:
Back4app Side:
import Parse from 'parse/react-native.js';
import AsyncStorage from '#react-native-async-storage/async-storage';
//Initializing the SDK
Parse.setAsyncStorage(AsyncStorage);
//Paste below the Back4App Application ID AND the JavaScript KEY
Parse.initialize('YOUR_APPLICATION_ID_HERE', 'YOUR_JAVASCRIPT_KEY_HERE');
//Point to Back4App Parse API address
Parse.serverURL = 'https://parseapi.back4app.com/';
//This is a hello function and will log a message on the console
Parse.Cloud.define("hello", async (request) => {
console.log("Hello from Cloud Code!");
return "Hello from Cloud Code!";
});
my app:
const helloFunction = await Parse.Cloud.run("hello");
I know the problem comes from the asynchronous function, but I can't find any solution. What am I doing wrong?
When using the cloud code, you do not need to do any kind of initialization as it is already done on the Back4app servers.
So in your main.js file please remove:
The import statements. Lines 2 and 3.
The Parse initialization. The lines 6,8, and 10.
To really answer the question, the error message is a false positive! Probably the online editor is not configured right, so it shows these warnings accidentally...
Just as the guide tells you, you can use the async keyword if you got a running 3.x Parse Server. It should be safe to use this, as per default Parse Server 4.x is used (the server can be changed via App Settings > Server Settings > Manage Parse Server).

How to connect to a Sqlite db from an HTML file via Javascript

I would like to insert data into a SQlite3 db by pressing a button from an HTML file.
In order to achieve this, I wrote a JS script.
Unfortunately, when I press the button, I get this error message in my console.log:
script.js:5 Uncaught ReferenceError: require is not defined
Then, I tried to convert my JS file with browserify but then I got this error:
Cannot read property '_handle' of undefined
Here my HTML and JS codes to reproduce the error:
HTML:
<head>
</head>
<body>
<div>
<label>SQLite3</label>
<button type="button">Connection</button>
</div>
<script src="script.js"></script>
</body>
JS:
function addData() {
const sqlite3 = require('sqlite3').verbose();
let db = new sqlite3.Database('./data.db');
db.run('INSERT INTO info (result) VALUES (10)', function(err, row) {
if(err) {
console.log(err.message);
}
console.log("entry added to table");
});
}
addData();
Browserify works around the problem that browsers don't have native support for the Node.js module system.
Browserify does not work around most other APIs that are provided but Node.js but not browsers. For example, Node.js has the fs module which allows you to access the file system of the computer the code is running on. Browsers, on the other hand, don't allow access except in very particular and limited ways.
Since new sqlite3.Database('./data.db') tries to read data from a file, it will not work in a browser.
Use a different API that is supported by browsers instead (such as IndexedDB or Web Storage.
Alternatively, if you want to share data between browsers, use Node.js to run a web server (e.g. with Express.js) and write a web service through which the database can be accessed.
You can't connect to sqlite databawe from client side you have to connect from server side language. Perhaps you can use NodeJS as server side programming language.
follow those steps then it will work
STEP1
Download and install node js from https://nodejs.org/en/download/
STEP2
Install npm by folloy this instruction
https://www.npmjs.com/get-npm
STEP3
Create Node js project by following this guides http://cassandrawilcox.me/setting-up-a-node-js-project-with-npm/
STEP4
Now you can install sqlite3 via npm.
After that you have to run server. If you are beginner then follow this
https://www.w3schools.com/nodejs/

Meteor - Meteor.Collection.get not defined in production

I'm trying to use Meteor.Collection.get(collection_name) (server side only) in production, it works well in development ; but as soon as I try to build my app with meteor --production, meteor throw
TypeError: Meteor.Collection.get is not a function
I suppose that Meteor.Collection.get was only made for debugging purposes (I can't find anything about it in the official documentation). Any idea how I can use it in production ?
I am not sure, where Meteor.Collection.get comes from in your code but I know the very reliable and long time battle proof dburles:mongo-collection-instances which allows you to retrieve a Mongo.Collection via it's name.
Add the package:
meteor add dburles:mongo-collection-instances
Create a collection:
// server/client
export const MyDocs = new Mongo.Collection('myDocs')
Get the collection:
// anywhere else
const MyDocs = Mongo.Collection.get('myDocs')
It works on the server and the client and runs fine in production.
Documentation: https://github.com/dburles/mongo-collection-instances
Edit: A note on --production
This flag is only there to simulate production minifaction. See the important message here in the docs: https://guide.meteor.com/deployment.html#never-use-production-flag
You should always use meteor build to build a production node app. More to read here: https://guide.meteor.com/deployment.html#custom-deployment

Meteor 1.0 MiniMongo not serving objects to the client side

I am working through the Discover Meteor tutorial, and even though the Posts = new Mongo.Collection('posts'); has all of its functions working on the server side Mongo shell, calling the Posts functions on the browser console is simply not working:
Posts.insert()
ReferenceError: Posts is not defined`
The collection is declared in my lib/collections folder in a posts.js file, as such:
Posts = new Mongo.Collection('posts');
if (Meteor.isServer) {
Meteor.publish('posts', function(){
return Posts.find()});
}
if(Meteor.isClient) {
Meteor.subscribe('posts');
}
`
Any ideas or suggestions? When I run db.posts.insert({title: "postname}) in the Mongo shell, the new post shows up instantly asynchronously in the browser, so I know the DB is functioning.
I'm pretty early on in the tutorial so I feel like this shouldn't be happening.
First( just to good practices), on console run this
Cd myApp
meteor remove autopublish
Now you need to Publish (server side), Subscribe(client side), all yours Collections
//server side
Posts = new Mongo.Collection('Posts');
Meteor.publish('Posts', function(){
return Posts.find()
});
/Client side
Posts = new Mongo.Collection('Posts');
Meteor.subscribe('Posts');
Hope This Works mate, and keep discovering Meteor
Are you using a web based cloud IDE?
If yes...
Do not use the javascript console that comes with your web based IDE. Run your output in a real browser like firefox or chrome and use their javascript console.

socket.io - ReferenceError: io is not defined

I am writing an application for Android 2.3.5 (that will also be compatible with iOS). I wish to transfer data from the app's HTML/Javascript to a Python program on a server (which uses the Twisted engine to retrieve the data).
I've tried many things and looked at various forums, answers, tutorials, and web pages--including most of them here--and can't find an answer. Here's the relevant Javascript I have in my index.html file:
<script src="socket-lib/socket.io.js"></script>
<script type="text/javascript" charset="utf-8">
function sendData() {
try {
var socket = io.connect('http://mywebsite.com:12345');
socket.on('connect', function(data) {
socket.send('Hello.');
socket.on('message', function (msg) {
socket.send('This is where I send data?');
});
});
}
catch(err) {
alert('ERROR: socket.io encountered a problem:\n\n' + err);
}
} // end of sendData
If you can't tell, I'm still pretty confused how this works; I can't even test anything. The error that keeps coming up is ReferenceError: io is not defined. Some sites used something like var io = require('socket.io');. But then it results in the same error: ReferenceError: require is not defined.
I put the socket-lib folder in assets/www, where any other Javascript source should go. This is also where the index.html file is. Many sites use <script src="/socket.io/socket.io.js"></script>, but this makes no sense to me. Many sites also imply the use of node.js, but I never see it anywhere.
How can I make this work?
Reply edits:
I tried it in Chrome, and it's giving me an Uncaught ReferenceError: require is not defined for the socket.io.js file. So I decide to source in require.js right before it. Then it gives the error Uncaught Error: Module name "socket.io-client" has not been loaded yet for context. Since I'm not using this, I care not. When I try the connection, though, it gives the same io is not defined error. When I define it as var io = require('socket.io'), the error is Error: Module name "socket.io" has not been loaded yet for context: _ http://requirejs.org/docs/errors.html#notloaded. I looked at the website, and it doesn't help me at all. When I try to put "require" as a function argument, another error occurs: TypeError: undefined is not a function.
I found the answer for anyone who gets immensely confused by the horrible lack of documentation of socket.io.
You cannot source /socket-lib/socket.io.js,
you must source http://yourwebsite.com:12345/socket.io/socket.io.js.
The server automatically does the rest for you.
I solved it myself by changing index.html to import the socket io client from bower, first i installed the bower component:
bower install socket.io-client
then i changed the reference in index.html to :
<script src="bower_components/socket.io-client/socket.io.js"></script>
Or file could be found at - lib/socket.io-client/dist/socket.io.js
I managed to blunder through this, and squandered about an hour, on something that turned out to be a very basic error.
When an function is not defined? Such as " Uncaught ReferenceError: io is not defined ". Does that not mean that the function is getting "used" before it is "created"?
In the part of my HTML file, that "calls" the javaScript files, it looked like this :
<script src='./js/playerChatter.js'></script> <!-- this one calls io -->
<script src="http://localhost:2019/socket.io/socket.io.js"></script><!-- This Creates io -->
and i changed it to this
<script src="http://localhost:2019/socket.io/socket.io.js"></script> <!-- This Creates io -->
<script src='./js/playerChatter.js'></script> <!-- this on calls io -->
So now the item "io", whether it is an object or function... Is actually getting created before it is getting used :D
Have FUN!
write server side code in socket.io.js file and try src="/socket.io/socket.io.js"
hope this will solve your problem
When getting socket.io to work with many other libraries using require.js I had same error, it turned out to be caused because of trying to load the socket.io.js file from the same /js folder than the rest of the other files.
Placing it in a separated folder, fixed it for me, you can see the code in this gist but all I changed for making it work, was this:
instead of:
socketio: 'socket.io',
Use:
socketio: '../socket.io/socket.io',
Not sure about the reason of this behavior, but I hope it helps you.
This looks like your browser cannot find the socket.io.js file. You could try opening the index.html on your computer with Firefox+Firebug or the Chrome Web Developer Tools and look at how the .js file is requested. On the other side, you could check the logs on the webserver serving the .js file whether there are any file not found errors.
The require function would be provided by e.g. RequireJS, but you would still need to configure the paths to your scripts correctly for it to work.
For me after debugging through all of the very helpful suggestions, it turned out to be simply that my node server had stopped. I had been running it manually in a terminal window during dev.
Make sure your node [yourservercode].js is running on the specified port! :-]
I use jspm.
Add this:
import 'btford/angular-socket-io/mock/socket-io';
In my case, using Unity WebGL with C# UnitySocketIO plugin, I need to add delay (1 sec) between Init and Connect, because the first method did not have time to add a new JS Socket object and code (listeners) to the page to work with it..
As mentioned in other answers, you have to use the complete URL.
<script src="http://127.0.0.1:5565/socket.io/socket.io.js "></script>
if it's giving you an error 404 please check whether io is properly instantiated on your server.js.If not please refer following to instantiate the io properly.
<script>
var socket = io();
</script>
In your server.js
const app = express();
const http = require('http'); //from express module
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
got to url /socket.io/socket.io.js and check if a js file is served or not if yes then instead of writing
var socket = io();
write
window.onload= function(){
var socket = io();
}

Categories