Cloud9 - Node.js fs can't open an html file - html

I do experiments with node.js and socket.io and it works fine locally.
I can read an html file and manage an interactive button for several users.
So i uploaded it on Cloud9 but i have an error ENOENT trying to find the html file.
It's in root (like in local) and the line is fs.readFile('ex.html' etc...
Here is the code of a test to open an html file and i have the enoent error on the console :
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('ex.html', function(err, data){
if(err) throw err;
response.end(data);
});
}).listen(process.env.PORT, process.env.IP);
Here is another program (full) that displays a blank page...
server :
var http = require('http');
var fs = require('fs');
// Creation du serveur
var app = http.createServer(function (req, res) {
// On lit notre fichier app.html
fs.readFile('app.html', 'utf-8', function(error, content) {
res.writeHead(200, {'Content-Type' : 'text/html'});
res.end(content);
});
});
var io = require("socket.io");
io = io.listen(app);
io.sockets.on('connection', function (socket) {
socket.on('joue', function () {
socket.broadcast.emit('joue2');
}); // joue
}); // connection
app.listen(process.env.PORT, process.env.IP);
client (app.html) :
<html><head> <title>Hello</title></head><body>
<button id="button">clic</button>
<div id="render">a</div>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
var button = document.getElementById('button');
var render = document.getElementById('render');
button.addEventListener("click", clique, false);
function clique() {
socket.emit('joue');
}
socket.on('joue2', function () {
if (render.innerHTML == 'a') {
render.innerHTML = 'clic multi';
} else {
render.innerHTML = 'a';
}
});
</script></body></html>
I have installed socket.io on the server and all files are in the root of the folder node.js.
I already asked to Cloud9 but they said it works for them...
Sorry for my english and if im a beginner.
Thank you for your help :)

I guess your ex.html file is in node.js directory.
Try fs.readFile('node.js/ex.html', ...

Related

Return undefined answer from multer

I am using multer in my nodejs application for uploading files. And angularjs for the front end part. Once I click upload image, on the console I am getting undefined answer. Can any one help me to solve the problem.
Here I am pasting the code.
server.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;
var multer = require('multer');
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/upload/');
},
filename:function(req,file,cb){
cb(null,file.originalname);
}
});
var upload = multer({storage: storage});
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use(express.static('public'));
app.get('/',function(req,res){
res.render('index',{ title: 'Upload image' });
});
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})
And here is my app.js angularjs code
var app = angular.module('app',['ui.router','ui.bootstrap','ngAnimate']);
$scope.img={};
app.controller('Ctrl',function ($scope,$http){
$scope.loadImage = function(){
$http.post('/loadImage',$scope.img).success(function(data){
console.log('Posted successfully');
}).error(function(data){
console.error('error');
})
};
And my HTML code:
<form ng-submit="loadImage()" enctype="multipart/form-data">
<input type="file" name="file" multiple />
<input type="submit" value="Upload Image" name="submit" />
</form>
On the console I am getting Undefined and Inside post. And on the browser console I am getting posted successfully Can any one please help me to solve this. Instead of undefined I should get loaded file information.
This how i used Multer to upload an image
var multer = require('multer');
exports.loadImage = function (req, res) {
var upload = multer({
inMemory: true,
limits: {fileSize: 1024 * 1024 }
}).single('newPicture');
upload(req, res, function (uploadError) {
if (uploadError) {
return res.status(400).send({ message: 'errorUploadingPicture' });
}
else {
var profileImage = 'No data uploaded';
// this is where the photo data is
if (req.file && req.file.buffer) {
profileImage = req.file.buffer;
}
return res.json(profileImage );
}
});
};
This is all assuming you are sending your file correct
try
var uploadType = upload.any()
and change
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
to
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});
if you are attempting to only get one file at a time then instead,
var uploadType = upload.single('file')
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});

export json object from .json file to vue through express and assign it to the variable

I would like to display on my page some data which I have in dsa.json file. I am using express with vue.
Here's my code from the server.js:
var data;
fs.readFile('./dsa.json', 'utf8', (err, data) => {
if (err) throw err;
exports.data = data;
});
Here's code from between <script> tags in index.html
var server = require(['../server']);
var data = server.data;
var scoreboards = new Vue({
el: '#scoreboard',
data: {
students: data
}
});
I am using requirejs (CDN) to require server between <script> tags in index.html.
index.html is in public directory whereas dsa.json and server.js are in the main catalogue.
Here are the errors I get in the client:
require.min.js:1 GET http://localhost:3000/server.js
require.min.js:1 Uncaught Error: Script error for "../server"
I think it has something to do with context and scope but I don't know what exactly.
I am using Chrome.
Your approach is completely wrong. You can't include the server script on your page. Also, I'm not a NodeJS ninja, yet I don't think that exporting the data inside the function will work -> exports.data = data.
The workaround:
Server side:
const fs = require('fs');
const express = require('express');
const app = express();
const data = fs.readFileSync('./dsa.json', 'utf8'); // sync is ok in this case, because it runs once when the server starts, however you should try to use async version in other cases when possible
app.get('/json', function(req, res){
res.send(data);
});
Client side:
var xhr = new XMLHttpRequest();
xhr.open('GET', '/json', true);
xhr.addEventListener('load', function() {
var scoreboards = new Vue({
el: '#scoreboard',
data: {
students: JSON.parse(xhr.response)
}
});
});
xhr.addEventListener('error', function() {
// handle error
});
xhr.send();

How to connect static HTML and CSS files to Node.js application?

I try to show a (static) HTML webpage via Heroku. I have followed this tutorial: https://www.youtube.com/watch?v=gAwH1kSODVQ but after many attempts it is still not working.
I'm rather new to coding, so if you can give concrete examples that would be great!
The following files have been pushed to heroku:
server.js
package.json
Procfile.js
(folder) public with index.html, main.css
//Server.js file:
var express = require('express'); //require express module in server.js file
var app = express();
var mongojs = require('mongojs');
var db = mongojs('birthdaylist', ['birthdaylist']);
var bodyParser = require('body-parser');
var http = require('http');
var port = Number(process.env.PORT || 3000);
app.use(express.static(__dirname + '/public')); //connect to html file
app.use(bodyParser.json());
app.get('/birthdaylist', function(req, res) {
console.log("The server has received a GET request.")
db.birthdaylist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/birthdaylist', function(req, res){
console.log(req.body);
db.birthdaylist.insert(req.body, function (err, doc){
res.json(doc);
});
});
app.delete('/birthdaylist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.birthdaylist.remove({_id: mongojs.ObjectId(id)}, function(err, doc){
res.json(doc);
});
});
app.listen(port, function () {
});
you should use:
app.listen(%PORT_NUMBER%, function () {
// some code here
});
Instead of:
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end('<h6>Hello worldsfasfd!</h6>');
});

How to transform CSV to JSON data on Node JS

I am using IBM Bluemix to make a web service for a school project.
I need to transform the .csv data I have in a directory in my computer into a .json file, so I can manipulate this information.
I am using the fast-csv package for Node JS, but I am having trouble with the code.
In the end of my .js file, there is a piece of code that is supposed to get the .csv file and convert it to JSON. I obtained it in the fast-csv documentation webpage.
When I run it, nothing happens and I can't fin out why. How can I check if the code is really getting the .csv file and transforming it into a .json one?
The Cambio.csv file is in the same directory of my .js one.
// Hello.
//
// This is JSHint, a tool that helps to detect errors and potential
// problems in your JavaScript code.
//
// To start, simply enter some JavaScript anywhere on this page. Your
// report will appear on the right side.
//
// Additionally, you can toggle specific options in the Configure
// menu.
function main() {
return 'Hello, World!';
}
main();/*eslint-env node*/
//------------------------------------------------------------------------------
// node.js starter application for Bluemix
//------------------------------------------------------------------------------
// HTTP request - duas alternativas
var http = require('http');
var request = require('request');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
//chama o express, que abre o servidor
var express = require('express');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
});
app.get('/home1', function (req,res) {
http.get('http://developers.agenciaideias.com.br/cotacoes/json', function (res2) {
var body = '';
res2.on('data', function (chunk) {
body += chunk;
});
res2.on('end', function () {
var json = JSON.parse(body);
var cotacao = json["bovespa"]["cotacao"];
var CotacaoDolar = json["dolar"]["cotacao"];
var VariacaoDolar = json["dolar"]["variacao"];
var CotacaoEuro = json["euro"]["cotacao"];
var VariacaoEuro = json["euro"]["variacao"];
var Atualizacao = json["atualizacao"];
console.log('url', req.originalUrl);
obj=req.query;
DolarUsuario=obj['dolar'];
RealUsuario=Number(obj['dolar'])*CotacaoDolar;
EuroUsuario=obj['euro'];
RealUsuario2=Number(obj['euro'])*CotacaoEuro;
if (VariacaoDolar<0) {
recomend= "Recomenda-se, portanto, comprar dólares.";
}
else if (VariacaoDolar=0){
recomend="";
}
else {
recomend="Recomenda-se,portanto, vender dólares.";
}
if (VariacaoEuro<0) {
recomend2= "Recomenda-se, portanto, comprar euros.";
}
else if (VariacaoEuro=0){
recomend2="";
}
else {
recomend2="Recomenda-se,portanto, vender euros.";
}
res.render('cotacao_response.jade', {
'CotacaoDolar':CotacaoDolar,
'VariacaoDolar':VariacaoDolar,
'Atualizacao':Atualizacao,
'RealUsuario':RealUsuario,
'DolarUsuario':DolarUsuario,
'CotacaoEuro':CotacaoEuro,
'VariacaoEuro':VariacaoEuro,
'RealUsuario2':RealUsuario2,
'recomend':recomend,
'recomend2':recomend2
});
var csv = require("fast-csv");
csv
.fromPath("Cambio.csv")
.on("record", function(data){
console.log(data);
})
.on("end", function(){
console.log("done");
});
});
});
});
The code did not work because it was missing views engine setup.
After adding the following lines after var app = express();:
// view engine setup
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
and creating a sample Cambio.csv on the application root directory (same dir as app.js):
$ more Cambio.csv
mercado,cotacao,variacao
bovespa,1234,-2.3
dolar,3.777,0.23
euro,4.233,0.12
I run node app.js and point my browser to:
http://http://localhost:6006/home1
Output was:
$ node app.js
server starting on http://localhost:6006
url /home1
[ 'mercado', 'cotacao', 'variacao' ]
[ 'bovespa', '1234', '-2.3' ]
[ 'dolar', '3.777', '0.23' ]
[ 'euro', '4.233', '0.12' ]

AJAX request on Node.js server

I am unable to make an AJAX request from my .html page to my node.js server for a JSON file. I've been reading on AJAX requests, but all I am able to make out is how to display the servers responseText.
It would be great if you could help me out, it would be even better if you could link me some tutorials on this, anyway this is what I've got at this moment:
server.js
var express = require('express');
var fs = require('fs');
var app = express();
app.get('/test', function(req, res){
var arr = new Array();
var rd = readline.createInterface({
input: fs.createReadStream('info.json'),
output: process.stdout,
terminal: false
});
rd.on('line', function(line) {
arr.push(line);
}).on('close', function(){
res.send(arr);
});
});
app.get('/', function(req, res) {
fs.readFile('test2.html',function (err, data){
res.writeHead(200, {'Content-Type': 'text/html','Content-Length':data.length});
res.write(data);
res.end();
});
});
app.listen(process.env.PORT || 3000);
test.html
<html>
<head>
<script>
function sendAjax(){
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState==4 && xmlHttp.status == 200){
console.log(xmlHttp.responseText);
}
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
}
xmlHttp.open("GET", "/test", true);
xmlHttp.send();
}
</script>
</head>
<body>
<input type="submit" onClick="sendAjax()" value="SendAjax" />
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
</body>
</html>
I know this may not look like much, I've been struggling with this, and the book I have (Node.js in Action) doesn't help me alot. But as I said, what I want is to display the .json info in the browser. Thx for reading
If I understand right, you may replace
document.getElementById("myDiv").innerHTML=xmlHttp.responseText;
with
var parsed = JSON.parse(xmlHttp.responseText);
var html = '';
for (var i = 0; i < parsed.length; i++) {
html += '<div>' + parsed[i] + '</div>';
}
document.getElementById("myDiv").innerHTML = html;
You may also try to replace
res.send(arr);
with
res.json(arr);
Update
Or maybe you just forgot to write this line in the beginning of server.js:
var readline = require('readline');