I'm trying to write a list of habit objects to a JSON file, but I can't figure it out. I'm doing this because I want to use this JSON file with node.js.
I've created a section with a class called "habits" that I want to fill this JSON file with, the section itself gets the habit objects from this piece of code:
var addHabit = function () {
var $new_habit = {
"name":"",
"value":0,
"goal":0,
"html": null
}
if ($(".habit-input input").val() !== "") {
$new_habit.name = $("#habitinput .name").val();
$new_habit.value = $("#habitinput .value").val();
$new_habit.goal = $("#habitinput .goal").val();
$new_habit.html = $("<p id="+uid+">").html("<span class=\"name\">"+$new_habit.name+"</span> <span class=\"val\">" + $new_habit.value + "</span>/" + "<span class=\"goal\">"+$new_habit.goal + "</span>"+
"<button class=\"plus\">+</button><button class=\"min\">-</button><button class=\"delete\">x</button><button class=\"mod\">modify</button>");
console.log($new_habit);
$(".habits").append($new_habit.html);
$(".habit-input input").val("");
$("#"+uid + " .plus").on("click", function (event) {
var val = parseInt( $(this).parent().find(".val").text());
$(this).parent().find(".val").text( val+1 );
event.preventDefault();
});
$("#"+uid + " .min").on("click", function (event) {
var val = parseInt( $(this).parent().find(".val").text());
$(this).parent().find(".val").text( val-1 );
event.preventDefault();
});
$("#"+uid + " .delete").on("click", function (event) {
$(this).parent().remove();
event.preventDefault();
});
$("#"+uid + " .mod").on("click", function (event) {
var val = parseInt( $(this).parent().find(".val").text());
var name = parseInt( $(this).parent().find(".name").text());
var goal = parseInt( $(this).parent().find(".goal").text());
$(this).parent().find(".val").text(val = $("#habitinput .value").val());
$(this).parent().find(".name").text(name = $("#habitinput .name").val());
$(this).parent().find(".goal").text(goal = $("#habitinput .goal").val());
event.preventDefault();
});
uid++;
};
};
I want to read the section "habits" into the JSON file so I can use it in this node.js file:
var express = require("express");
var url = require("url");
var http = require("http");
var fs = require('fs');
var port = 3000;
var app = express();
app.use(express.static(__dirname + "/client"));
//logger component
app.use(function (req, res, next) {
console.log("[LOG] %s %s", new Date(), req.url);
next();
});
http.createServer(app).listen(port);
//clients requests habits
app.get("/habits", function (req, res) {
console.log("Habits requested!");
res.sendfile('Habit/client/habits.json');
});
What I hope to achieve is that when I go to localhost:3000/habits in my browser that I get all the habit objects in JSON format.
At the moment when I go to localhost:3000/habits I get this {"type":"Buffer","data":[123,13,10,32,32,32,32,34,121,101,121,34,32,58,32,49,50,13,10,125]}
Any help would be greatly appreciated
You're getting a buffer back from the GET/habits. Need to convert it to a something you can read
try calling toString('utf-8')
OR
import bodyParser from 'body-parser';
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Related
I am trying to parse a JSON string upon loading the page but I get the following error in the web dev tools: GET http://ipaddress/CulturalEvents/calWrapper 404 not found (Note: ipaddress is the address for our IIS web server). When I click on the error I get the following error: Failed to load resource: the server responded with a status of 404 not found.
Here is my index.js
var titles = new Array();
var descriptions = new Array();
var count = 0;
// Function to cycle through events on display
function changeText() {
$('#evtName').html(titles[count]);
$('#evtDesc').html(descriptions[count]);
if (count < titles.length - 1) {
count++;
} else {
count = 0;
}
}
$(document).ready(function () {
$.ajax({
url:'/CulturalEvents/calWrapper',
type: 'GET',
dataType: 'json',
success: function(calJSON){
let eventCheck = 0;
var today = new Date();
var yyyy = today.getFullYear();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0');
today = yyyy + mm + dd;
console.log(today);
for (let i = 0; i < calJSON.length; i++){
if (calJSON[i].startDT == today){
eventCheck = 1;
} else {
eventCheck = 0;
}
if (eventCheck == 1){
titles.push(calJSON[i].summary);
if (calJSON[i].description == ""){
descriptions.push("No description.");
} else{
descriptions.push(calJSON[i].description)
}
} else {
titles.push("No events today.");
descriptions.push("If you know of an event that is not displayed feel free to contact the Diversity Equity and Inclusion committee.")
}
}
}
});
// Rotate through events
changeText();
setInterval(changeText, 10000);
});
It can't find my ajax url '/CulturalEvents/calWrapper'. Note I can run this locally and look for the endpoint /calWrapper and it works perfectly fine, but when I run it on the IIS server it stops working.
Here is my app.js as well:
// C library API
const ffi = require('ffi');
// Express app
const express = require('express');
const app = express();
const path = require('path')
const port = process.env.PORT
const fs = require('fs');
app.use(express.static('public'));
// Send HTML
app.get('/CulturalEvents/', function(req, res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
// Send style
app.get('/CulturalEvents/style.css', function(req, res) {
res.sendFile(path.join(__dirname + '/public/style.css'));
});
// send JavaScript
app.get('/CulturalEvents/index.js', function (req, res) {
res.readFile(path.join(__dirname + '/public/index.js'), 'utf8', function(err, contents){
res.send(contents);
});
});
// Wrapper function for c library
let wrapper = ffi.Library('./bin/libcalWrapper', {
'calWrapper': [ 'string', [ 'string' ] ]
});
app.get('/CulturalEvents/calWrapper', function (req, res) {
var tempStr = JSON.parse(wrapper.calWrapper(__dirname + "/multiculturalcalendar2021.ics"));
res.send(tempStr);
});
app.listen(port, () => {
console.log(__dirname + '/public/index.js');
});
Also the directory structure is as follows:
CulturalEvents/
public/
index.js
index.html
style.css
app.js
package.json
web.confi
So , I have been try to display my variables "pares", "impares" ,"ninguno" in real time as the image below I used app.get and inside that a response.write to print de varibles, but the problem is if I want the varaibles to update, I need to reload the page everytime, is there anyway to print them in real time?,enter image description here
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var reload = require('reload');
var http = require('http');
var server = http.createServer(app);
var impares = 0;
var pares = 0;
var ninguno =0;
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
app.post('/arduino', function(request, response) {
console.log("Arduino asking data");
var stringInform = (Object.keys(request.body)).toString();
var stringA = stringInform.split("|");
var dato1= parseInt(stringA[0],10);
var dato2 = parseInt(stringA[1],10);
response.send('Hello Arduino');
Parimpar(dato1,dato2);
response.end();
console.log(dato1);
console.log(dato2);
console.log(ninguno);
});
app.get('/arduino', function(request, response) {
response.write('PARES:'+ pares + ' '+ 'IMPARES:' + impares + ' ' + 'NINGUNO:'+ ninguno);
response.end();
});
app.listen(8080);
function Parimpar(c,i)
{
if (c%2 == 0 && i%2 == 0)
{
pares = pares +1;
// return pares;
}
else if (c%2 != 0 && i%2 != 0)
{
impares = impares + 1;
//return impares;
}
else
{
ninguno = ninguno +1 ;
//return ninguno;
}
}
You Can Use Web-sockets To Emit Events When The Values Are Updated . The Easier Way Is to Setup A socket.io webserver and emit values to all the connected values.
Check Out https://socket.io/
I'm trying to store emails from sendgrid via the inbound webhook using node, express and multer. There is an example on sendgrids site as below:
var express = require('express');
var multer = require('multer');
var upload = multer();
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.use(multer());
});
app.post('/parse', upload.array('files', 3) function (req, res) {
var from = req.body.from;
var text = req.body.text;
var subject = req.body.subject;
var num_attachments = req.body.attachments;
for (i = 1; i <= num_attachments; i++){
var attachment = req.files['attachment' + i];
// attachment will be a File object
}
});
var server = app.listen(app.get('port'), function() {
console.log('Listening on port %d', server.address().port);
});
This code throws an error when an email with an attachment is sent. The error is "unexpected field". I assume that the declaration for array.upload("files",3) is where the issue lies. Has anybody solved this?
You can solve this by using .any() when you don't the field name (see documentation for any()
Here's an example code
app.post('/parse', upload.any() function (req, res) {
var from = req.body.from;
var text = req.body.text;
var subject = req.body.subject;
var num_attachments = req.body.attachments;
for (i = 1; i <= num_attachments; i++){
var attachment = req.files['attachment' + i];
// attachment will be a File object
}
});
I'm currently trying to retrieve data from a sqlite query in node.js, the sql function is on a diferent file so i'm exporting it as a module and then call the function from the index.js. But when i try to retrieve the data the function returns a null value.
Here is my code
Index.js
var express = require("express");
var body_parser = require("body-parser");
var app = express();
var db = require('./dbhandler.js');
app.set("view engine", "jade");
app.get("/data",function(req,res){
let data = db.select();
res.send(data);
});
app.get("/",function(req,res){
res.render("index");
});
app.listen(8888);
dbhandler.js
var sqlite3 = require("sqlite3");
const file = "hr";
exports.select = function (){
var lista = [];
var db = new sqlite3.Database(file);
db.all("SELECT * FROM usuarios", function(err,rows){
let contador = 0;
rows.forEach(function (row) {
lista[contador] = row.nombre + ";" + row.cedula + ";" + row.edad + ";" + row.pais;
});
});
db.close();
return lista;
}
Node is asynchronous!!!. lista is returned from the module before the db.all function completes.
You either need to pass a callback into the select function or return a promise. The callback approach would look something like this:
exports.select = function (cb){
var lista = [];
var db = new sqlite3.Database(file);
db.all("SELECT * FROM usuarios", function(err,rows){
if(err) return cb(err);
let contador = 0;
rows.forEach(function (row) {
lista[contador] = row.nombre + ";" + row.cedula + ";" + row.edad + ";"
+ row.pais; });
db.close();
return cb(null, lists);
});
}
I have the following middleware function
var bodyParser = require('body-parser'),
fs = require('fs');
module.exports = function(req, res, next) {
// Add paths to this array to allow binary uploads
var pathsAllowingBinaryBody = [
'/api2/information/upload',
'/api2/kpi/upload',
];
if (pathsAllowingBinaryBody.indexOf(req._parsedUrl.pathname) !== -1) {
var date = new Date();
req.filePath = "uploads/" + date.getTime() + "_" + date.getMilliseconds() + "_" + Math.floor(Math.random() * 1000000000) + "_" + parseInt(req.headers['content-length']);
var writeStream = fs.createWriteStream(req.filePath);
req.on('data', function(chunk) {
writeStream.write(chunk);
});
req.on('end', function() {
writeStream.end();
next();
});
} else {
bodyParser.json()(req, res, next);
}
};
The files is being transfered correctly however sadly the next() in the
req.on('end', function() {
writeStream.end();
next();
});
is called before it is done writing all data to the new file.
My question is what am i doing wrong? And how can i fix it?
Use the writable file stream's close event to know when the file descriptor has been closed.
Replace this:
var writeStream = fs.createWriteStream(req.filePath);
req.on('data', function(chunk) {
writeStream.write(chunk);
});
req.on('end', function() {
writeStream.end();
next();
});
with this:
req.pipe(fs.createWriteStream(req.filePath)).on('close', next);