dynamic image in meteor - javascript

What is the standard way of serving and storing dynamic images in meteor
PS. I cannot use any package that uses public or subscribe. So any use of mongo apis like Collection.find() in the client, has to be served by calling some function to server.

I am not sure what you mean by "dynamic images". From where I'm standing, here are some options.
The easy way: you store and serve them directly from your public directory. If you have an image in /public/images/lolcat.png you can load it using the url /images/lolcat.png. However, be warned about one thing: as long as you are in development more, the server will reload each time you add or modify one of your public assets.
The less easy way, you can use nginx to serve your content. See more info about it here: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-meteor-js-application-on-ubuntu-14-04-with-nginx
The tricky way, you fork a package like file-collection and you replace the publications with server methods returning a cursor (I never did that but I assume it is possible).
You would then call your method like below, and use result as a cursor.
Meteor.call("meteorMethod", dataObject, function(error, result){
if(error){
console.log("error", error);
}
if(result){
}
});

Related

Fastest redirects Javascript

My main function is I am creating a link-shortening app. When someone entered a long URL, it will give a short URL. If the user clicked on the short link it will search for the long URL on the DB and redirect it to the long URL.
Meantime I want to get the click count and clicked user's OS.
I am currently using current code :
app.get('/:shortUrl', async (req, res) => {
const shortUrl = await ShortUrl.findOne({short: req.params.shortUrl})
if (shortUrl == null) return res.sendStatus(404)
res.redirect(shortUrl.full)
})
findOne is finding the Long URL on the database using ShortID. I used mongoDB here
My questions are :
Are there multiple redirect methods in JS?
Is this method work if there is a high load?
Any other methods I can use to achieve the same result?
What other facts that matter on redirect time
What is 'No Redirection Tracking'?
This is a really long question, Thanks to those who invested their time in this.
Your code is ok, the only limitation is where you run it and mongodb.
I have created apps that are analytics tracker, handling billion rows per day.
I suggest you run your node code using AWS Beanstalk APP. It has low latency and scales on your needs.
And you need to put redis between your request and mongodb, you will call mongodb only if your data is not yet in redis. Mongodb has more read limitations than a straight redis instance.
Are there multiple redirect methods in JS?
First off, there are no redirect methods in Javascript. res.redirect() is a feature of the Express http framework that runs in nodejs. This is the only method built into Express, though all a redirect response consists of is a 3xx (often 302) http response status and setting the Location header to the redirect location. You can manually code that just as well as you can use res.redirect() in Express.
You can look at the res.redirect() code in Express here.
The main things it does are set the location header with this:
this.location(address)
And set the http status (which defaults to 302) with this:
this.statusCode = status;
Then, the rest of the code has to do with handling variable arguments, handling an older design for the API and sending a body in either plain text or html (neither of which is required).
Is this method work if there is a high load?
res.redirect() works just fine at a high load. The bottleneck in your code is probably this line of code:
const shortUrl = await ShortUrl.findOne({short: req.params.shortUrl})
And, how high a scale that goes to depends upon a whole bunch of things about your database, configuration, hardware, setup, etc... You should probably just test how many request/sec of this kind your current database can handle.
Any other methods I can use to achieve the same result?
Sure there are. But, you will have to use some data store to look up the shortUrl to find the long url and you will have to create a 302 response somehow. As said earlier, the scale you can achieve will depend entirely upon your database.
What other facts that matter on redirect time
This is pretty much covered above (hint, its all about the database).
What is 'No Redirection Tracking'?
You can read about it here on MDN.

Send a textbox value to another [duplicate]

I'm doing project in nodejs and html .can anybody help how to set value to text field in html from server.js. For example I've text field with id 'name' on index.html. i use res.body.name = 'nametest' .but its not working .please give me a simple example . Thank you friends
In order to set a field from the server, you want to make it a preset value which you define when sending the HTML or you want to set it dynamically later on. The first option is easy, the second one a bit advanced.
Let's look at option 1. This is just a very basic example! Please don't use this in production.
index.html
<!DOCTYPE html>
<html>
<head><!-- your stuff here --></head>
<body><input type="text" name="someVal" value="{{someVal}}"></body>
</html>
This might be your HTML. Just but a distinctive placeholder where you want your value to go. There might be better techniques out there to do this, but for the sake of simplicity I chose this way.
server.js
var http = require('http');
var fs = require('fs');
http.createServer((req, res) => {
fs.readFile('index.html', (err, data) => {
if (err) {
res.writeHead(500);
res.end(err);
return;
}
data = data.toString().replace(/\{\{someVal\}\}/, 'your value here');
res.writeHead(200);
res.end(data, 'utf8');
});
}).listen(8080);
This server.js will open a HTTP server on port 8080. It will try to read index.html from the same directory. If it fails, it will send the error message to the client, else it will replace your placeholder in your HTML with your value and then send the modified content to the client.
If that's all you want to do, PHP might do a better job for you (but that's just my 2 cents :) )
Option 2 is a lot more elaborate. You would have to either use AJAJ (Asynchronous Javascript and JSON) which requires the client to know when to fetch the value or you could make use of websockets which enable the server to push a value to the client. For either of those there are a lot of tutorials out there which are a lot more detailed than anything I could put together for you here.
If you want to use those techniques, but are a bit unsure about their iomplementation, you might want to look at frameworks like Meteor and Socket.IO
You can't set a client-side thing from the server-side. They're absolutely different physical layers.
What you need is AJAX to request a resource from your Web app to your NodeJS server-side app, and set what you put in you response to the whole text field.
Maybe you'll need to take a look at ExpressJS to build a simple RESTful service to share resources between your client and server tiers.

How can I write an array to another .js file?

So I'm making a webApp that involves thousands of API queries. Since the API has a limit on the amount of queries I can send it per day, I was wondering if I could simply run the query loop a single time and then write the resulting objects to an array in a new file.
is this possible?
You want to make calls, then create cache, then use cache instead of call.
Are you on client side or in server side js ?
Client side will be tricky, but server side is easy :
Files can be a cache, so does a DB or a lot of tools (memcached, etc..).
Sure, just send the array to JSON.stringify() and write it to a file.
If you are using Node.js it would look something like this:
function writeResponse(resp, cb)
{
fs.writeFile('response.json', JSON.stringify(resp, null, 2), function (err) {
if (err) console.log(err);
if(cb) cb();
});
}
If you are in a browser you can use the Web Storage API which allows storage in key/value pairs up to 10Mb. If that doesn't work, maybe write a quick Node.js server that works as a caching proxy. A quick google search suggests that you might be able to find one ready to deploy.
You could probably use local storage, which is accessible across your domain, and will remain on the users computer indefinitely. Perhaps something like this:
function getData(){
var data = localStorage.getItem("myData");
if(data === null){
data = makeQuery();
localStorage.setItem("myData", data);
}
return data
}

Communication between an express node server and its displaying html

Really fast, this question may have already been asked, but I am not totally clear on the terminology and have had no success when searching for a solution.
I am attempting to create a simple web application that can receive get and post requests. Then, I would like to take the information I receive from these requests and use them in a javascript file embedded in html that is displayed. I think it may be more clear with code. This is my app.js:
var express = require('express');
var app = express();
var assert = require('assert');
app.use(express.static('javascript'));
app.get('/', function(req, res) {
res.render('index.jade');
});
app.listen(3000);
I would then like to be able to take information received from a get or post request, specifically in JSON format, and then be able to use it in javascript that I have linked to index.jade. To make matters slightly more confusing in index.jade the only line is:
include map.html
So ideally I would be able to get the information to javascript in that html file.
I want to be able to pretty continuously update map.html using javascript based on frequent get and post commands.
This could be a very simple solution, I am pretty new with web application programming in general, and I have been struggling with this problem. Thanks in advance, and ask if you need any clarification.
I think you need to understand what you are doing. You are creating a web server using node.js. Express framework simplifies that for you. The official documentation of express is pretty great. You should refer that especially this link.
Now, in your application, you need to create endpoints for GET and POST requests. You have already created one endpoint "/" (root location) that loads your home page which is the contents of the file index.jade. A small example is :
app.get('/json', function (req, res) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({ a: 1 }));
});
Jade is a templating engine which resolves to HTML. You should refer its documentation as well. Since as you said, you are not very familiar with these, you could simply use HTML as well.
After this tasks are quite simple. In your javascript, using ajax calls you can access the GET or POST endpoints of your server and do the desired actions.
Hope it helps!
The way I get it you want to be able to call an endpoint (lets assume /awesome) pass some info and then write to a Javascript file that you can then reference in your html.
Something like the below would write a main.js file in your public folder. You can make it write whatever you want.
var fs = require('fs');
fs.writeFile("/public/main.js", "console.log('Hello!')", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
You can then reference /public/main.js in your html.
Check that: Writing files in Node.js
If I misunderstood your intentions, apologies. :)
So you want to reviece continuously data from the server maybe web sockts are an option for you http://socket.io/docs/
This way u will open a stable connection from the client to the server. This is a great way if u want to get updates done by other clients.
If you want to trigger the changes by the client then ajaxs calls(http://www.w3schools.com/ajax/) as hkasera mentioned are the way to go.

Meteor methods on server

When I write meteor methods for collections I usually put them in a shared directory so they can be simulated on the client for fast speeds. However is this secure? Should I put methods in the server directory and if so which kind of methods?
This is not the way meteor is supposed to work for the general case. You are supposed to implement most of your collection methods (update, insert, remove) client side only, and check the updates rights server side.
If you have a collection with some posts, do not make a Meteor.call('addNewPost', newPost). And the a Posts.insert(...) in the addNewPost meteor method server side. This would be the classic way with a REST API ; but this is meteor :)
You go client side directly for a Posts.insert(...). This will be displayed client side right away and will try to update the base server side.
Then server side, you have to set extensive permissions :
Posts.allow({
'insert': function(userId, doc) {
// Check if the user exists
// if he has the right to insert
// if what he tries to insert is ok for you
// ...
},
'update': function(userId, docs, fields, modifier) {
// same, width the fields, the doc, the user...
},
'remove': function(userId, docs) {
// same again
}
});
You can allow() or deny()on anything you can do on a collection. This may seem weird but this is the real basis of good latency compensation. It may be a HUDGE security breach if you do not know how to set up your permission as they need to be. But if you know how to do that, there are absolutely not security issue.
(my advice is to deny everything but the specific elements you want to allow)
So :
the user updates his database client side with a client side method : myCollection.update()
he sees the results
meteor does its magic to send it to the server
the server check if this is allowed
if yes, write in base and send to the other subscribers
if not, send a request to revert the change client side
yes. you can make it safe and have shared directory for collections. Meteor latency compensation feature works only if you have collections in both server and client.
if you are using a shared code for collections you must do these.
remove insecure, autopublish packages
use publish/subscribe
configure allow/deny rules for each collection
more on meteor security.
http://security-resources.meteor.com/

Categories

Resources