I am making a website for students to give test... I will be also hosting it. But I want to make the code such that a particular student can give the test only once a day. So, I thought of placing a text (.txt) file on the server and read and write the dates, the student last gave the test. But, I came to know about the fact that JavaScript cannot access server-side files. So, is there a way to do the thing I want to?
Note : I want to do both reading and writing into the file
You'll need to use a client-server model:
Client makes a HTTP request to the server
Server receives the request and reads the file on behalf of the client
Here's a bare-bones example in express:
import express from 'express';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import level from 'level';
const app = express();
app.use(cookieParser());
const {Level} = level;
const lastTakenDates = new Level('lastTakenDates', {valueEncoding: 'json'});
const jsonParser = bodyParser.json();
app.post('/start', jsonParser, async (request, response) => {
const username = somehowGetUsername(request.cookies.session);
const now = Date.now();
const lastTaken = await lastTakenDates.get(username);
if (!lastTaken || (lastTaken + 1000 * 60 * 60 * 24) < now) {
await lastTakenDates.put(username, now);
response.status(200).send("OK");
return;
}
response.status(403).send("You can only take the quiz once a day");
});
I am answering my question because I found a very easy way to accomplish the task. Its just simply easy to use PHP. You can write a simple PHP script for handling the file and then activate that script using an AJAX request which can be posted through JQuery. The text to be written can be set as a cookie using javascript and that cookie will be accessed through PHP and the task will be accomplished !!!!
Also, a big thanks to all the sincere effortsof #Richie Bendall to help me
Related
I have a proprietary math formula written in a javascript function that I need to make available for a website to use it without them actually having access to the code itself.
Is it possible?
The idea is to make the formula available online without people being able to read the code. I have no idea how to do it.
I read about private packages on npm, but it seems to restrict prople who can use and read the code. I need them to use it but not read it.
If the code is run on the client's machine in any way, it will be possible for any sufficient dedicated and persistent user to find it, eventually; all code that runs on a page can be found through the browser devtools.
The only way for true privacy for such a thing would be to not send the code that implements the formula to the client in the first place. Set up a server, if you don't already have one, and create a very simple API for it - one that takes the inputs for the formula as, say, a POST request, runs the formula that calculates the result on the server, and responds to the client with the result.
Use node.js to create an express server that listens for incoming requests and then send back the result to the client in the response
const express = require('express');
const app = express();
function proprietaryFormula(x, y) {
// the formula goes here
return x + y;
}
app.get('/formula', (req, res) => {
let x = req.query.x;
let y = req.query.y;
let result = proprietaryFormula(x, y);
res.send(result);
});
app.listen(3000, () => {
console.log('started listening on port 3000');
});
The website can call this API to access the formula's functionality, and the code for the formula is kept on the server and never exposed to the client-side.
I would like to forward all incoming messages to some other number with the number to which I got the reply on Twilio,
For example:
I have a Twilio number say "+14444444444" to which I got the reply from number say: '+15555555555' and I would like to forward all messages to number '+19999999999'.
So I would like to forward all messages on number '+19999999999' which should be received from '+15555555555', not from '+14444444444',
Will anyone please let us know if there is an API in Twilio that can do a trick using nodeJs.
Note: The SMS forwarding number can be dynamic and in that case, we cannot use Twiml, if we can use Twiml so please let us know how to set dynamic forwarding number.
Also got the following link that says how to forward SMS but is not relevant to approach we are trying to accomplish using nodeJS:
https://support.twilio.com/hc/en-us/articles/223134287-Forwarding-SMS-messages-to-another-phone-number
Thanks, any help will be appreciated.
Updated Answer
Thanks, #Alex and #Piyush for clarifying the question:
Really sorry about that! Thanks for clarifying. If I understand you correctly now, you want to forward a message to another number, but preservice the original number from the message. Unfortunately, there's not a way to do this. You can forward the message and include the original sender in the message body, but there's no way to replace the actual sender as the original.
Let me know if I understood that correctly this time and if there's anything else I can help with.
Old Answer (Message forwarding with own number)
You can use TwiML dynamically when using our helper libraries, so that should be something you can setup using Node. When your webhook sends your message to your Node application, you can check the body of the message, and make a conditional SMS request or conditionally point to different TwiML based on the content of the body. Here's an example of how to setup a conditional reply for your incoming messages based on the message body in Node:
https://www.twilio.com/docs/sms/tutorials/how-to-receive-and-reply-node-js
While this example is for replying to messages, it shows you the principles of how conditional TwiML can work.
You would just have add a "to" number you want to forward the message to in the message request.
Below is the example of conditional forward.
const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/', (req, res) => {
const twiml = new MessagingResponse();
twiml.to = "+1234567890 // Your number here.
if (req.body.Body == 'hello') {
twiml.message('Hi!');
} else if (req.body.Body == 'bye') {
twiml.message('Goodbye');
} else {
twiml.message(
'No Body param match, Twilio sends this in the request to your server.'
);
}
res.writeHead(200, { 'Content-Type': 'text/xml' });
res.end(twiml.toString());
});
http.createServer(app).listen(1337, () => {
console.log('Express server listening on port 1337');
});
Let me know if that helps and if you have anymore questions on how to set this up.
I'm having a little problem with thread blocking algorithms.
I have a route that generates a zip with huge size files.
The flow works like this:
GetUrls > ObtainHugeSizeBuffer > GenerateZIP > UploadZIPToCloud
I cannot modify the timeout response default time of 2 minutes with the express-timeout module. I've also been trying to break the loopholes in the .nextTick() function.
I've even tried to look over queueing but I don't think that applies in this situation.
Do you guys have any idea how to expand the response time? - I strictly need to for one route only.
// start the server
const server = app.listen(8080);
// increase the timeout to 4 minutes
server.timeout = 240000;
This is the easiest way to extend server timeout, but it affects everything, not just one method.
In your case (you wan't it only for on specific route):
'use strict';
const ms = require('ms');
const express = require('express');
const router = express.Router();
router.route('/upload-files')
.post(
setConnectionTimeout('12h'),
require('./actions/upload-files').responseHandler
);
function setConnectionTimeout(time) {
var delay = typeof time === 'string'
? ms(time)
: Number(time || 5000);
return function (req, res, next) {
res.connection.setTimeout(delay);
next();
}
}
exports.router = router;
Not my code, found it in this thead: Node Express specific timeout value per route
You need to google better :)
I've been working on a server and a push notification daemon that will both run simultaneously and interact with the same database. The idea behind this is that if one goes down, the other will still function.
I normally use Swift but for this project I'm writing it in Node, using Mongoose as my database. I've created a helper class that I import in both my server.js file and my notifier.js file.
const Mongoose = require('mongoose');
const Device = require('./device'); // This is a Schema
var uri = 'mongodb://localhost/devices';
function Database() {
Mongoose.connect(uri, { useMongoClient: true }, function(err) {
console.log('connected: ' + err);
});
}
Database.prototype.findDevice = function(params, callback) {
Device.findOne(params, function(err, device) {
// etc...
});
};
module.exports = Database;
Then separately from both server.js and notifier.js I create objects and query the database:
const Database = require('./db');
const db = new Database();
db.findDevice(params, function(err, device) {
// Simplified, but I edit and save things back to the database via db
device.token = 'blah';
device.save();
});
Is this safe to do? When working with Swift (and Objective-C) I'm always concerned about making things thread safe. Is this a concern? Should I be worried about race conditions and modifying the same files at the same time?
Also, bonus question: How does Mongoose share a connection between files (or processes?). For example Mongoose.connection.readyState returns the same thing from different files.
The short answer is "safe enough."
The long answer has to do with understanding what sort of consistency guarantees your system needs, how you've configured MongoDB, and whether there's any sharding or replication going on.
For the latter, you'll want to read about atomicity and consistency and perhaps also peek at write concern.
A good way to answer these questions, even when you think you've figured it out, is to test scenarios: Hammer a duplicate of your system with fake data and events and see if what happen is OK or not.
So, I was told that passing around the request and or response variable in nodeJS is "bad practice". But this means that most of your code has to be in the server.js file, making it cluttered and kind of ugly.
How can you modularize your nodejs server, passing around req/res appropriately and be able to organize your code into separate files?
For example, I would like to split my socket routing, .get and .post into different files, but still be able to use the callback parameters like so:
app.io.route("disconnect", function(req,res) { <--- these params
db.query("UPDATE player_data SET online=0 WHERE id="+mysql.escape(req.session.user));
req.io.broadcast("event", {msg:req.session.username+" has logged out!"});
app.io.broadcast("reloadXY");
});
As of right now they're all in one file and I don't like that.
I think what the person meant by 'passing around' was something like this (in plain express):
app.get('/kittens', function(req, res) {
db.doAthing(req);
updateSomethingElse(res);
upvoteThisAnswer(res);
});
That is, passing around the two variables beyond the first function. This is bad because it becomes increasingly difficult to figure out where the call actually ends. One little res.end(500) in updateSomethingElse can cause the whole house of cards to come tumbling down.
It's perfectly ok (in fact, standard to the point of being the default in express) to declare that callback elsewhere (usually the /routes directory of your project.)
// app.js
var user = require('./routes/user')
, kittens = require('./routes/kittens');
// express stuff...
app.get('/settings', user.getSettings);
app.get('/fur', kittens.shed);
Then, in routes/user.js:
exports.getSettings = function(req, res) {
// Note how we're passing around properties of req/res, not the objects themselves.
db.getUserSettings(req.user.id).then(function(settings) {
res.render('settings', settings);
});
};
This video from TJ Holowaychuk (the guy who wrote Express and a ton of other Node infrastructure that we all use) helped me take Express modularization to the next level. Basically you can make individual apps in their own folders and consume them as middleware very easily. I have managed to extend this technique to socket.io with some tricks.
http://vimeo.com/56166857
You should not pass req and res to another modules but pass callbacks from another modules to route.
It should look like.
var someModule = require("./someModule")
app.get("/someAction", someModule.handleSomeAction) ;
If You want to have post and get in another modules You should pass reference to app (from express()) once to that module and operate on that.
For example :
var express = require("express") ;
var app = express();
var get_handler = require("./get_handler ")
var post_handler = require("./post_handler ")
get_handler.init(app);
post_handler.init(app);
and in post/get_handler :
var app;
exports.init = function( eApp){
app = eApp;
// operate on app
}