node.js - using weld with express? - html

I'm new to node.js, and attempting to use weld to render templates on the server-side and using express as the router.
However the examples for node.js doesn't show serving the content, and am fuzzy on how this would work with express:
var fs = require('fs'),
jsdom = require('jsdom');
jsdom.env(
'./test.html',
['./jquery.js', './weld.js'],
function(errors, window) {
var data = [{ name: 'hij1nx', title : 'code slayer' },
{ name: 'tmpvar', title : 'code pimp' }];
window.weld(window.$('.contact')[0], data);
}
);
Help or example would be appreciated.

I think something like this would work. Haven't tested though.
var fs = require('fs'),
jsdom = require('jsdom'),
app = require('express').createServer();
app.get('/', function(req, res) {
jsdom.env('./test.html', ['./jquery.js', './weld.js'], function(errors, window) {
var data = [{
name : 'hij1nx',
title : 'code slayer'
}, {
name : 'tmpvar',
title : 'code pimp'
}];
window.weld(window.$('.contact')[0], data);
res.send(window.document.innerHTML); //after the welding part we just send the innerHTML
window.close(); // to prevent memory leaks of JSDOM
});
});
app.listen(3001);

Related

NodeJs: Display function's result in html

How can I get results of my function NODEJS in HTML there is my code:
var elasticsearch = require('elasticsearch');
var express = require('express');
var app = express();
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
function getAllMetadata() {
client.search({
index: 'info',
scroll: '30s',
}, function getAll(error, response) {
response.hits.hits.forEach(function (body) {
allresp.push(body.hits);
})
console.log('Voilà le nombre de réponse : ' + allresp.length);
if (response.hits.total !== allresp.length) {
client.scroll({
scrollId: response._scroll_id,
scroll: '30s'
}, getAllMetadata);
}
});
}
getAllMetadata();
PS: PLZ how can i display my result "function" in HTML
You need to make a view and use a templating language like ejs to use javascript variables in a view. The view will be a ejs file which will be converter to html and rendered.
Here is a good example - https://github.com/chovy/express-template-demo
In that repo there is a index.ejs which calls the function inspect(session)

AngularJS File Upload to Backend Express Server

I am trying to do a file upload using angularjs, using angular-file-upload library (https://github.com/danialfarid/angular-file-upload)
Here is my code
// ===============================My HTML File===========================
<input type="file" ng-file-select="onFileSelect($files)">
// ===============================My Controller==========================
var $scope.formObj = {
name: "Test"
};
var fileToUpload;
$scope.onFileSelect = function (file) {
fileToUpload = file[0];
};
// POSt request to /api/items
$scope.addItem = function() {
console.log($scope.formObj);
$scope.upload = $upload.upload({
url: '/api/items',
method: 'POST',
data: { myObj: $scope.formObj },
file: fileToUpload
}).success(function(data, status, headers, config) {
console.log("success");
});
};
// ================================My Backend=============================
// This is the function that will receive POST request to /api/items
exports.create = function(req, res) {
console.log(req.body); // req.body is just an empty object. ==> {}
// apparently, I found all the data to be in req._readableState.buffer[0]
// in the form of a buffer
var buffer = req._readableState.buffer[0];
// trying to console.log the buffer.toString, resulting in something similar to this
// { name: "Test", image: Object }
console.log(buffer.toString());
return res.send(200);
};
So my backend received the formObj with all its properties and values, however, the actual file data itself, whether in the form of buffer, or base64, or whatever, never gets received.
I wonder why. This is my first time working with file uploading, so I don't understand the concept.
Please point me in the right direction
If you are using Latest version of Express, you'd notice that
app.use(express.multipart()); is no longer bundled with express.
So do the following configuration changes. in express.js
var multer = require('multer');
app.use(multer({ dest: './uploads/'}));
You'd find that after doing this you would find the data and file , in req.body req.file respectively.
Hope it helps

mongoose return json list of tags specified as subdocuments

so i am having this problem that keeps me busy for the past 4 days, i am having a schema and subdocument schema like this:
var mongoose = require( 'mongoose' ),
Schema = mongoose.Schema;
var ProjectSchema = new Schema({
name: String,
author: String,
category: String,
description: String,
tags: [TagSchema]
});
var TagSchema = new Schema({
name: String,
date: Date
});
mongoose.model( 'TagSchema', TagSchema );
mongoose.model( 'Project', Project );
and what i want to have is a list of all tags of all ProjectSchemas, whatever i try i either get NONE or just the ones of the most current Project. i just dont know further because whatever i do i always end up failing on this one. what am i doing wrong, is there no such thing as a findAll for mongoose?
app.get('/tags.json', function(req, res) {
TagSchema.find({}, function ( err, tags ){
var json = JSON.stringify(tags);
console.log(json);
tags = tags.map(function (tag) {
return tag.toObject();
});
console.log(json == JSON.stringify(tags));
res.json(json);
});
});
and
app.get('/tags.json', function(req, res) {
Project.find(function (err, projects) {
projects.forEach( function( project ){
res.json(project.tags);
});
});
});
and anything else i tried just returned
[ ]
or errored out...
(additionally i wonder, how can i make sure that if i add a tag to a project and its already existant how i can keep it from adding.)
You are trying to call find on the schema, when you should be trying to call it on a model.
If you change the bottom of your file to:
var TagModel = mongoose.model( 'TagModel', TagSchema );
var ProjectModel = mongoose.model( 'ProjectModel', Project );
and then in your app.get function calls:
app.get('/tags.json', function(req, res) {
TagModel.find({}, function ( err, tags ){ //changed this to the model instead of the schema
var json = JSON.stringify(tags);
console.log(json);
tags = tags.map(function (tag) {
return tag.toObject();
});
console.log(json == JSON.stringify(tags));
res.json(json);
});
});
and
app.get('/tags.json', function(req, res) {
ProjectModel.find(function (err, projects) {
projects.forEach( function( project ){
res.json(project.tags);
});
});
});
Models are constructors compiled from your schema definitions and represent the documents that can be saved and queried from the db.
When you use TagSchema in its own model and embedded in ProjectSchema like you are, it's important to understand that the docs in the tags collection and the docs in the tags array of project docs have no inherent connection. So if you save tags as part of a project, those won't end up in the tags collection unless you explicitly add them to that as well.
A few specific problems in your posted code:
You need to define TagSchema before you use it in ProjectSchema.
You should be passing ProjectSchema into the mongoose.model call, not Project.
Keep your schema and model names separate as it's not clear what's what in your code.
with the help of #alawson421's code and some array magic it works perfectly, thanks again #JohnnyHK for showing me the difference between a schema and a model. heres the working fix:
app.get('/tags.json', function(req, res) {
ProjectModel.find(function (err, projects) {
var taglist = [];
projects.forEach( function( project ){
//console.log(JSON.stringify(project.tags));
project.tags.forEach( function( tag ){
console.log(tag);
taglist.push(tag.name);
});
});
res.json(taglist);
});
});
and the output is:
[
"test",
"meep",
"lalela",
"another test",
"ihopethisworks",
"noderocks",
"i am not a mongo",
"ice cream rocks"
]

Getting static data from a json file into backbone model

I have the following code and was wondering why my data isn't getting pulled into my model? I'm using a static json file and I'm guessing this might be my problem but can't seem to find any documentation about it.
var DataModel = Backbone.Model.extend({
initialize: function () {
console.log('initiliazed model')
},
url: "data/data.json"
});
var StructureView = Backbone.View.extend ({
initialize: function () {
console.log('initiliazed view')
_.bindAll(this);
this.model.fetch();
this.render();
this.model.on('change',this.render);
},
el : '#ev-wrapper',
render: function () {
$('#ev-wrapper').empty().append(Handlebars.compile($('#ev-template').html())(this.model.toJSON()));
$('.ev-asset-loader').fadeOut('slow');
}
});
var structureView = new StructureView({model: new DataModel()});
You need to call fetch. This will issue an AJAX request using url
var model = new DataModel();
model.fetch();
Open Firebug or your favorite browser's network console to see AJAX requests and check if it's OK

node.js server, displaying HTML file which has jqGrid plugin included.

I have a simple HTML file which includes jqGrid plugin. I am using jqGrid plugin to have a tree grid in my HTML page.
Now, I am trying to host this HTML file in node.js server. My server.js looks like this
var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting...');
var filePath = '.' + request.url;
console.log('filePath : '+filePath);
if (filePath == './')
filePath = './tree.html';
var extname = path.extname(filePath);
console.log('extname : '+extname);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
} else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
} else {
response.writeHead(404);
response.end();
}
});
}).listen(8125);
So far, I am able to display my HTML content in browser [http://localhost:8125/]
Part of my HTML(tree.html) file looks like this
jQuery("#treegrid").jqGrid({
url: 'tree.json',
datatype: 'json',
//mtype: 'GET',
colNames: [/* "ID", */"Col 1", "Col 2",.. ],
colModel: [/* {
name: 'id',
index: 'id',
width: 1,
hidden: true,
key: true
}, */{ ...
If you can notice, I have specified 'tree.json' as URL attribute to load the tree grid. That is just reading a static file to load the tree grid with sample data.
Problem : Now, when I try to access my HTML file using [http://localhost:8125/]
I get an 404 Not Found error for [http://localhost:8125/tree.json]
Quick Solution : I can specify the relative path of the file 'tree.json' and it works.
Both my HTML file tree.html and tree.json are in the same directory (/tree) and I start my node.js server from command prompt (terminal) like this
tree> node server.js
I would like to know where I can place my tree.json in order to make my HTML work as intended.
Please feel free to ask any clarification.
Thanks in advance
You use the line
var filePath = '.' + request.url;
in your code which seems a little strange. Probably in case of request of 'tree.json' you will have .tree.json as the value of filePath instead of ./tree.json which you probably want to have. I think you should fix the code here.
Moreover it would be good to set 'application/json' as the value of contentType variable in case of .json extension in the same way like you set 'text/javascript' and 'text/css' for '.js' and '.css' files.