Save a JSON file to server in express (node) - javascript

Having this function in express that writes a JSON file on a folder
var savingtheJson=function(path, jsonObject, callback){
jsonfile.writeFile(file2, jsonO, callback);
}
I will like to know how can I access/read this file from the browser once is saved.
If I do this:
savingtheJson('/json/myfile.json', jsonObj, function(){
console.log("done it!");
});
When I go to the browser and I type:
http://localhost:8080/json/myfile.json
Of course I get an error from express "Cannot Get ...." cause I think is trying to resolve it like an specific request
How can I store this file into the static folder declared for this goal
(app.use(express.static(__dirname + '/public'))?
How can I access this file once is saved?

First you need to define which folder is going to be exposed as public, so that you can save your json file inside there.
You can use the built-in middleware express.static for this purpose.
Below in the example I have created a endpoint called /users?name=wilson&age=32 which receives query data in order grab user's information as name and age for then you can save it as file named person.json.
So after you consume the above endpoint mentioned, you will be able to consume your file with something like http://localhost:4040/person.json successfully.
var express = require('express');
var app = express();
var port = 4040;
var fs = require('fs');
app.use(express.static('public'));
app.get('/users', function(req, res) {
var name = req.query.name;
var age = req.query.age;
var person = {
name: name,
age: age
};
savePersonToPublicFolder(person, function(err) {
if (err) {
res.status(404).send('User not saved');
return;
}
res.send('User saved');
});
});
function savePersonToPublicFolder(person, callback) {
fs.writeFile('./public/person.json', JSON.stringify(person), callback);
}
app.listen(port, function() {
console.log('server up and running at port: %s', port);
});

Related

AJAX: Listing out the content of a directory. Unable to resolve URL

I'm trying to display some images contained in a folder, inside a div. I'm using AJAX to do that in a JavaScript file called edit that is one directory away from the index route. I'm using Node.js. The code I have written is as follows.
var folder = "../images/emojies/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
// some code
});
}
});
I get this error:
"GET /images/emojies/ 404"
The weird thing is that when I go to this for example:
"/images/emojies/image.png", It finds the directory with no errors!
It's like it can't find folders but it can find files?
routing code if needed:
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'xx' });
});
/* GET edit page. */
router.get('/edit', function(req, res, next) {
res.render('edit', { title: 'xx' });
});
You could have done something like follows.
var app = require('express')();
var http = require('http').Server(app);
var fs = require('fs');
var clients = 0;
app.get('/images/emojies', function(req, res) {
var path = "public/images/emojies/"; //Could be obtained from req.path however, needs to resolve the path properly.
fs.readdir(path, function(err, items) {
res.send(items); // items is an array
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
/images/emojies would be the endpoint that you would contact and you could use your existing AJAX request as follows.
var folder = "/images/emojies";
$.ajax({
url : folder,
success: function (data) {
//Under data, you have a stringified array of the file names.
}
});
The best thing about this method is that it gives you more fine-grained control over the file types and file names that you are going to expose, especially given that you are going to expose a part of your file system.
You can use path module to fix your problem:
https://nodejs.org/api/path.html
I think that it should look like this:
var folder = path.normalize("../images/emojies/");
In Nodejs when you access to folder you have to write folder root with ./ sign.
For example
var folder = "./../images/emojies/";//Firstly you have to write "./" it access to the same folder where your file is then go up another folder
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
// some code
});
}
});

Using redis in an Express route

I want to simply be able to store a value in a key in one route
/api/foo?redisKey="1" (set value for id=1)
then I want to get the value in another route.
/api/bar?redisKey="1" (get value for id=1)
However, redis is async so you have to wait for it to connect
client.on('connect', function() {
//perform redis operations
});
I'm not sure how to synchronize this in my router.
I am going to assume you're using redis for your client library.
In your express route file, you do not want to create the connection during each request. Instead you will instantiate your redis client outside of the express middleware function, and use it during requests.
Here's a sample app:
var redis = require("redis");
var client = redis.createClient();
var express = require('express')
var app = express()
// GET request
// example: curl "localhost:3000/api/foo?redisKey=1"
app.get('/api/foo', function (req, res) {
var redisKey = req.query.redisKey
client.get(redisKey, function (err, reply) {
if(err){ res.status(400).send(err.getMessage()); return; }
res.status(200).send(reply.toString())
});
})
// for setting, use POST request
// example: curl -X POST "localhost:3000/api/foo?redisKey=1&redisValue=helloWorld"
app.post('/api/foo', function(req, res){
var redisKey = req.query.redisKey,
redisValue = req.query.redisValue
// assuming value is also a string in URL query string
client.set(redisKey, redisValue, function (err, reply){
res.status(200).send(reply.toString())
});
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})

Node.js parsing form data using formidable

Hey guys I am new to node, and trying to setup a file/image upload script.
I was able to setup node on my VPS and following this example I also set up the app and it is working great.
https://coligo.io/building-ajax-file-uploader-with-node/
It is using formidable and express
However I'd love to also parse a form where people can add their name and the files get uploaded into a folder containing their names.
I was able to get the folder creation working using mkdirp, however even after many hours of research (formidable api, express api, and more) I can't get the form to parse the name.
I suspect that the upload.js (which sends the data to the node app) does not work.
At the moment a new folder with a random string is created for each upload, but I'd love to be able to parse the entered formname.
Any idea how to get it working? I'd appreciate any help/hints.
app.js
var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var mkdirp = require('mkdirp');
var crypto = require("crypto");
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'views/index.html'));
});
app.post('/upload', function(req, res){
var ordner = crypto.randomBytes(20).toString('hex');
mkdirp('/home/myfolder/fileupload/'+ordner, function (err) {
if (err) console.error(err)
else console.log(ordner)
});
var form = new formidable.IncomingForm();
form.multiples = true;
form.uploadDir = path.join(__dirname, '/'+ ordner);
form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name + Date.now()+'.jpg'));
});
form.on('field', function(field, userName) {
console.log(userName);
});
form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});
form.on('end', function() {
res.end('success');
});
form.parse(req);
});
var server = app.listen(3000, function(){
console.log('Server listening on port 3000');
});
Thanks
The upload.js is unchanged and I simply added another input to the view.
You can do this by sending the parameters through the POST like so
app.post('/upload/:userName', function(req, res){
var username = req.params.userName
mkdirp('/home/myfolder/fileupload/'+username, function (err) {
if (err) console.error(err)
else console.log(ordner)
});
The rest of your code pretty much stays the same.
EDIT: Your ajax would look something like this
var username = 'GetThisValueFromTheUser'
$.ajax({
url: '/upload'+username,
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful!');
}
});
Note: You can send parameters by using /:parameter in your POST or GET requests, from then on it is easy to use those parameters however you want.

how to run different .js file in one server.js file in NODE JS?

this is demo.js file and i want to use this file in server.js file so that i can use diffrent js files in one server file.
Demo.js:
app.get('/add User', function (req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/project';
MongoClient.connect(url, function (err, db) {
var collection = db.collection('users');
collection.find({name: 'shruti'}).toArray(function (err, result) {
console.log(, result);
db.close();
});
Server.js:
var a = require('./demo.js');
vr http=require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write(a);
res.end();});
server.listen(7860);
A possible sample would look like :
demo.js
var myModule = {
defineRoutes: function(router){
//do something...
}
}
module.exports = myModule;
server.js
var myModule = require('demo.js');
myModule.defineRoutes(router);
As stated, you need to export.
When you do:
var item = require("mymodule");
Require returns an object, which is a reference the value of module.exports for that given file - in your case demo.js.
You can write your modules a few ways as some people have shown you. Because it is encapsulated you basically are identifying what is public or can be called. Few ways to write it - you could also do:
module.exports = {
yourCall: function () {
console.log("stuff here");
}
};
As stated by #ishann, who is dead on here, you are writing something you assume might be populated. Going to a database and returning is an asynchronous call - so it will take time to go do that and then for the results to be returned.
Based on your structure - ideally what you want to do is assign the route ( "/addUser" ) which will pass in the response object to you:
app.get('/add User', function (req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/project';
MongoClient.connect(url, function (err, db) {
var collection = db.collection('users');
collection.find({name: 'shruti'}).toArray(function (err, result) {
console.log(, result);
db.close();
// set the type
res.writeHead(200, {"Content-Type": "application/json"});
res.write(result);
});
Just looks like your code needs a bit of reorg, but separting concerns is good. You might want to also check out Express as a framework for node.

can't delete record from mongodb dbase using backbone.js

Following "Developing Backbone js" http://addyosmani.github.io/backbone-fundamentals/#talking-to-the-server (search "parse function")
on click "Delete": the book is not deleted from the server (dbase) even with this "parse" function operating OK... the DELETE http command is given, with the correct ID for the book... but this doesn't delete it from the dbase...
generated URL command looks like this:
DELETE http://localhost:4711/api/books/5417ff846b205d9c05000001
... this is triggering the following function in server.js
app.delete( '/api/books/:id', function( request, response ) {
console.log( 'Deleting book with id: ' + request.params.id );
...
... but the DELETE command never "returns" (in FF Console you just get the spinner, which doesn't go away)...
In your server.js, setup your server as follows:
// Module dependencies.
var application_root = __dirname,
express = require("express"), // Web framework
path = require("path"), // Utilities for dealing with file paths
mongoose = require('mongoose'); // MongoDB integration
//Create server
var app = express.createServer();
// Configure server
app.configure(function () {
app.use(express.bodyParser()); // parses request body and populates req.body
app.use(express.methodOverride()); // checks req.body for HTTP method overrides
app.use(app.router); // perform route lookup based on url and HTTP method
app.use(express.static(path.join(application_root, "public"))); // Where to serve static content
app.use(express.errorHandler({ dumpExceptions:true, showStack:true })); // Show all errors in development
});
//Start server
app.listen(4711, function () {
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});
// Connect to database
mongoose.connect('mongodb://localhost/library_database');
//Schemas
var Book = new mongoose.Schema({
title:String,
author:String,
releaseDate: Date
});
//Models
var BookModel = mongoose.model('Book', Book);
Try creating the delete route as follows:
app.delete('/api/books/:id', function(req, res){
console.log('Deleting book with id: ' + req.params.id);
return BookModel.findById(req.params.id, function(err, book){
return book.remove(function(err){
if(!err){
console.log('Book removed');
return res.send('');
} else {
console.log(err);
}
});
});
});
And test it via AJAX:
$.ajax({
url:'/api/books/5417ff846b205d9c05000001',
type: 'DELETE',
success:function(data, textStatus, jqXHR){
console.log("Post resposne:");
console.dir(data);
console.log(textStatus);
console.dir(jqXHR);
}
});

Categories