I am trying to make a webpage and server where a user can enter in recipes and have them sent to (using JSON) the server and have the server store them in a file so that if the server is closed and reopened the user can request for something they've entered previously and can get it. I know how to send the JSON object both to the server and how to send the JSON object back to the client. I should note this can't use jquery.
What I need help with is how to store it in a file server side and get the contents from it later using a node.js server. They should all be stored in the same directory and I need to know how to get a list of the recipes in that directory. I've tried looking around but I can't seem to find the answer :(.
Example:
user makes a recipies
{ name:"cheese n waffles"
time:90,
ingredients:"cheese, eggs and waffles",
equipment:stove
};
Browser sends the JSON object to the server.
Client asks for a list of the recipes stored.
user asks for the recipe for spaghetti.
what I need help with:
server gets a list of the recipes it has stored
server takes the JSON object and stores it in /serverRootDir/recepiesStorage
server accesses /serverRootDir/recepiesStorage and gets the spaghetti recipe
You should be using a JSON based database such as MondoDB
It takes some learming however implementing with a text file will eventually become much more work and will function poorly
(Posted on behalf of the OP).
I have solved the problem. I will be using:
To read a file (access a recipe): fs.readFileSync() or fs.readFile().
To save a file (update a recipe): fs.writeFileSync() or fs.writeFile().
To get an array of files in a directory (retrieve the list of recipes): fs.readdirSync() or fs.readdir().
Related
I am writing my first web application with Javascript and WebGL. For now I am running the app on localhost from Apache. The app needs to work with data that is provided instantly. Until now I worked with AJAX calls that happen during runtime which doesn't work out for my purposes anymore. So instead of serving individual files from Server to Client when asked, I want the application to load all files from the Server to Client side at initialization time (I want this to happen automatically at the start so I don't have to add every new file as a url in the html index). I understand I should do this with Server Side scripting; probably with PHP since I have a Apache localhost? I have different folders which hold my necessary resources in a uniform dataformat (.txt, .png and .json). So what I want to do is, before the Javascript app starts, look through the folder and send one object per folder that holds filenames as keys bound to filedata. Is my intuition right that I need to do that with PHP? If yes, where do I start to tell my application what to do when (first start serving files with php, then start the javascript app)? How do I do this on localhost? Should I already think about extending my toolset (e.g. using nodeJS on ServerSide(locally for now))? If so what lightweight tools do you propose for this kind of work? I feel I am missing some design principles here.
EDIT:
Keep in mind that I don't want to specifically call a single file... I am already doing that. What I need is a script that automatically serves all the files of a certain folder on the server to the client side at init time of the app before the program logic of the actual application starts.
Your question is kind of broad so I'll try my best. Why does AJAX not work for real-time data but loading all the files once does? If you're working with real time data, why not look into a websocket or at the bare minimum, AJAX queries?
If you want to pass data from the server to the client, you will need to use a HTTP request no matter what. A GET request or POST request is necessary for the client to request data from the server and receive it as a response.
You could theoretically just pass the data from PHP straight to the view of the application (which is technically done through a GET request whenever a user requests data such as .php files from the server) but this isn't as flexible as if Javascript had access to the data. You can do some hacks and 'transfer' the data from the view to Javascript with some .value methods, but this isn't ideal and can be prone to some security holes. This also means data is only being passed once.
So what would need to happen is that the data would need to be processed upon initialization and then immediately transferred to the client by use of Javascript and HTTP requests.
So if you want Javascript to have access to the data and use it in variables or manipulate it further, then you'd need to use an HTTP request such as GET or POST which is called by Javascript. Otherwise, you need to immediately pass the data to the view upon initialization (through PHP), but this means you can't work with real-time data because the data is only being passed once when there is a page refresh.
Example of scandir():
<?php
//scandir() returns filenames, not data from files
$fileArray = scandir('datafolder/') //this is a relative path reference to the folder 'datafolder'
$finalArray = [];
foreach($fileArray as $filename){
tempArray = [];
$file = fopen('datafolder/' . $filename, 'r'); //im pretty sure scandir only retrieves the filenames and not the path, so you might need to append the filepath so your script knows where to look
$tempArray = fgetcsv($file, 1024); //temp array to hold contents of each iteration of foreach loop
array_push($finalArray, $tempArray); //this will store the data for later use
}
Or the data can be used however, depending on what it is. Say, if you need to combine the data from multiple .csv files, you can read each file and append it to a single array. If you want to read multiple distinct files and preserve the independence of each file, you can create multiple arrays and then pass back a single JSON encoded object that contains each file's data as a separate attribute of the object such as:
{
'dataOne': [0,1,2,3,4,5,6...],
'dataTwo': ['new', 'burger', 'milkshake'],
'dataThree': ['Mary', 'Joe', 'Pam', 'Eric']
}
Which can be created with a PHP associative array using one of the following methods:
//assuming $arrayOne is already assigned from reading a file and storing its contents within $arrayOne
$data['dataOne'] = $arrayOne;
// or
array_push($data['dataTwo'], $arrayTwo);
// or
array_push($data, [
'dataThree' => ['Mary', 'Joe', 'Pam', 'Eric']
]);
Then $data can simply be passed back which is a single array containing all the different sets of data, if each set needs to be distinct.
I have been working on a library which enable a website to add a comment section to their website.
The idea was to keep it as lightweight as possible thus I preferred to use JSON for basic data storage like comment's message, website and username. All of these data is public and can be access directly via JSON. I don't mind this since comments are going to get display publicly anyway.
However, the problem arises when I want a user to be notified when someone replies to their comment. Email is there in input field but I don't want it to be stored in the public JSON file. Is there any other server side data storage schema where I can store the email privately and at the same time use those emails from server side scripts to send email?
MySQL and others will make the library clunky, so that's out of the list.
Or even beside these conditions is there any other possible way to do this?
What you need is APIs and not a data source. A data source is a truth where all data lives. Like in your example, if you have email in your data, it will always be there. Unless you keep email field separately.
The way is to create api that will output required data from JSON files (or database). You can choose to hide the data that you don't want to show.
This way, you only expose the api, instead of the file name directly, which has risks of being modified or altered or hacked very easily.
Other way without using API is to have multiple JSON files.
One file will have basic data, and other will have confidential data, along with a foreign key like unique key that'd map the confidential or other data with the main record.
Example:
Comments.json:
{
"comments": [{userId: 1, ...},{...}]
}
CommentDetails.json
{...}
Users:
[
1: {"username": "", "email": "asdas#asdas.com",...}
]
You can use a database like MongoDB, that stores JSON documents, to keep the data of users and comments.
Then, the users collection will not be sent completely to the user, filterint the emails and other sensitive data.
Create a second JSON file, or CSV file for that matter, which is kept private, that maps users to their emailIDs.
Interesting project you are attempting, btw. Good luck!! :)
Why not just use a .htaccess in a directory where the data is stored and use something like "Deny from All"?
Your scripts could access then, but no user's browser.
Assuming there will be a mail server involved, can you host a web service with two endpoints?
Endpoints:
sends emails; takes an sender guid instead of an email address
stores an email; takes an email address and returns a sender guid
This web service could then be used by your library from any www accessible server. At the web service host the emails could be stored in the format of your choice. You will also want to secure you web service to prevent others from triggering mail notifications.
I'm doing a project which I want to send sensor's data to Firebase database. This connection must be via GPRS. To set or to push any data to Firebase database, it should be done using javascript and HTML, but the Arduino can't use javascript directly. Is there any way to make the connection?
I have a website. Would it be helpful to do the connection?
I will be really thankful if someone gave me a simple steps to follow.
Thank you in advance.
You could request web site links ( http request) from the arduino.And in this request you can pass details to the database.This is how the data is stored to the database from Arduino.
I am bit back about firebase database.
But let me tell what we did for storing data to a normal database.We made a PHP script such that if its link is requested with data ,it would store the data to the database.Then we made Arduino code in such a way as to request that link each time with the corresponding value to be stored.So if you can do PHP scripting for firebase data entry then its easier ( just request that link from Arduino).I think PHP insertion to firebase database is available.
You can also pass data to a website too using the above method ( simple modification in url would do that ,pass data to be stored).But the problem is how you would store it to the database from that webpage.If you have a way for that you can try it too.
I am learning about AJAX using W3school resources, and there is a phrase in this URL that I do not understand: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
It is about when POST should be used when using AJAX. It says:
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server).
Sending a large amount of data to the server (POST has no
size limitations).
Sending user input (which can contain unknown
characters), POST is more robust and secure than GET.
What does, A cached file is not an option (update a file or database on the server). mean?
if a file is cached it is stored locally on the clients machine which means that the data is already present and there is no need to go get it from a server. The reason this isn't an option for the post (it is but not best practice) is because the posts job is to send data to the server with the intention of updating a record or a file (sometimes if it's a really small change to the configuration of the server you would store it in a .json or .config or .txt file. This could be a post to update that file) / or database record.
The post will hide the data being sent (kind of, you won't see it in the URL unlike a GET Request which will show the name=value pairs in the URL). Post request is meant to update a piece of data.
It's impossible to update the server data with the local cached data - because if you update the local file/data it's not updating on the server, which is accessed via RESTful CRUD (GET/GET:ID/POST/PUT/DELETE) (Create, Read, Update, Delete) patterns
I am trying to write my first chrome extension. The workflow goes something like this -When the extension is installed and active if a user hovers over a specific product/ID displayed on the page, the extension retrieves related vendor data about the product with the ID.
This is how I thought about this:
Use jQuery attr to access the ID on mouse over.
Post this ID to a retrieve.php file with .post() method
The retrieve.php file retrieves the data from database
Display the data in a tool tip on the web page.
I have some queries for the above process:
I am able to get this working on a local XAMPP server but how will it work online as the chrome extension will not have access to server. What is the way around to retrieve data without using PHP?
I am able to get the logic working but am unable to place these in respective files - Will all my logic reside in background.js ?
Any suggestions on getting this started will be much appreciated.
You could build a very simple API on your server that responds with JSON to any request it receives after processing it. Like this:
{"firstVar":"foo","secondVar":"bar" }
Your chrome extension can then make an xmlhttp request to this server and and process the returned data.(You could also use JSONP and wrap the response in a callback function which will execute as soon as you have the reponse)
The JS extension will be able to deal with the JSON nicely as it can understand that format so you can then choose to display the data in whatever way you want.
Essentially, what you want is a server that can take an ID posted to it and return the corresponding date in a nice and readable format. And a chrome extension that can make an request to a server and then process the response. Build and test them separately (keep positing an ID to the server and see the response and for your JS side at first instead of making requests to your unfinished API just set a static response to begin with which will be the same as an expected response.