How to implement download file from heroku server in nodejs - node.js

I have a nodejs application where I have created project structure. package.json and index.js files, one json file also which I want that user can download it.
This is how my project structure
I have deployed nodejs application on heroku server. It is running perfectly, able to access index.js
How I can implement a functionality here so users can download swagger.json also. I tried to access this like https://heroku-address/swagger.json but it is showing only "Hello World"
index.js
var http = require("http");
http.createServer(function (request, response) {
// Send the HTTP header
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/plain'});
// Send the response body as "Hello World"
response.end('Hello World\n');
}).listen(process.env.PORT);

Let's start with defining server and app variables,
var express = require('express')
var app = module.exports = express();
Now,To show a tags on which if users click file will be downloaded,below is code to show links,
app.get('/', function(req, res){
res.send('<ul>'
+ '<li> package.json.</li>'
+ '<li> swagger.json.</li>'
+ '</ul>');
});
Now,When user clicks on one of the above link then code shown below will be executed,and file will be downloaded,
app.get('/:file(*)', function(req, res, next){
var file = req.params.file
, path = __dirname + '/' + file;
res.download(path);
});
finally code for listening on port,
app.listen(8080);
console.log('Express started on port %d', 8080);
So,your full server.js file will look like,
var express = require('express')
, app = module.exports = express();
app.get('/', function(req, res){
res.send('<ul>'
+ '<li>Download package.json.</li>'
+ '<li>Download swagger.json.</li>'
+ '</ul>');
});
app.get('/:file(*)', function(req, res, next){
var file = req.params.file
, path = __dirname + '/' + file;
res.download(path);
});
app.listen(8080);
console.log('Express started on port %d', 8080);

Related

How to recieve a file using request.get()?

I am writing a server that is meant to serve and receive files. It is written in node.js, using express.js. I also have a client, also written in node, which is meant to send a request to the server and receive the files on the server.
Server-side
const express = require("express");
const app = express();
const file = "./samplefiles/Helloworld.txt";
app.get("/", (res)=>{
res.download(file);
});
module.exports = app; //this exports to server.js
const http = require("http");
const app = require("./app.js);
const port = 8080;
const server = http.createServer(app);
server.listen(port, () => {
console.clear();
console.log("server running");
})
Client-side
const request = require("request");
request.get("http://localhost:8080/", (req, body) => {
console.log(body);
console.log(res);
});
If I try to access it by my browser I am asked what I want to do with the file, it works. However, Is I run my client-side code it prints the body and the res(being null). I expected the file name and it's content to be in the body but only the content of the file was in the body.
I want to receive the whole file, is possible, or at least get the name of it so that I can "make" a copy of it on the client-side.
Change code your server side to:
const port = 8080;
const express = require("express");
const app = express();
const path = require('path');
app.get("/", function(req, res){
res.sendFile(path.join(__dirname, 'app.js'));
});
app.listen(port, () => {
console.clear();
console.log("server running");
});
Change code your client-side to:
var request = require('request');
request('http://localhost:8080/', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print data of your file
});
You need to install request npm i request for client side
You can serve up any files you want with express static method:
app.use(express.static('public'))
in this case just put all the files you want to serve in folder called public and then you can access it by localhost:8080/Helloworld.txt.
I ended up working around it.
I sent the file name as a header and was thus able to create a replica of the file I wanted to download using the body info and the filenameheader.

How to run project based on Nodejs, when getting message like Unresponsive script?

When run nodejs project, the message like Unresponsive script
I got one project on git-hub based on angularjs-rickshaw. It is based on nodejs, bower.
Project: ngyewch/angular-rickshaw
Demo of above project: DEMO
I want to run above project on my local system. I successfully installed every thing (nodejs, npm, bower). But When I type http://localhost:3000/ I get nothing, I am new in Nodejs, please help me on this. What will be the correct url?
[neelabh#localhost angular-rickshaw]$ node server.js
connect.multipart() will be removed in connect 3.0
visit https://github.com/senchalabs/connect/wiki/Connect-3.0 for alternatives
connect.limit() will be removed in connect 3.0
Server running at http://localhost:3000/
I am getting following type of message if I ran 1.http://localhost:3000/ or 2. http://localhost:3000/#/home
server.js
'use strict';
var fs =require('fs'); //for image upload file handling
var express = require('express');
var app = express();
var port =3000;
var host ='localhost';
var serverPath ='/';
var staticPath ='/';
//var staticFilePath = __dirname + serverPath;
var path = require('path');
var staticFilePath = path.join(__dirname, serverPath);
// remove trailing slash if present
if(staticFilePath.substr(-1) === '/'){
staticFilePath = staticFilePath.substr(0, staticFilePath.length - 1);
}
app.configure(function(){
// compress static content
app.use(express.compress());
app.use(serverPath, express.static(staticFilePath)); //serve static files
app.use(express.bodyParser()); //for post content / files - not sure if this is actually necessary?
});
//catch all route to serve index.html (main frontend app)
app.get('*', function(req, res){
res.sendfile(staticFilePath + staticPath+ 'index.html');
});
app.listen(3000, function () {
console.log('Server running at http://' + host + ':' + port + '/');
})
//app.listen(port);
//console.log('Server running at http://'+host+':'+port.toString()+'/');
Looking at https://github.com/ngyewch/angular-rickshaw/blob/gh-pages/server.js, console.log('Server running at http://'+host+':'+port.toString()+'/') should be a callback to listen call. Otherwise console.log always gets executed, even if the server doesn't start properly.
The correct way is:
app.listen(3000, function () {
console.log('Server running at http://' + host + ':' + port + '/');
});
For staticFilePath and in other path-related parts you should use path.join:
var path = require('path');
var staticFilePath = path.join(__dirname, serverPath);
Ultimately it's best to move all static files to public directory and serve it with express.static middleware:
'use strict';
var express = require('express');
var app = express();
var port = 3000;
app.use(express.static('public'));
app.listen(port, function () {
console.log('Server running at http://' + host + ':' + port + '/');
});

Node express static files

I'm working with node and express. I try to create a simple server using express.static. I have a file in the following folder on my server :
client/index.html
However, when I try this url : http://myServer.com/index.html, the server answers that :
Cannot GET /index.html
Here, you will find my used code :
var express = require('express');
var app = express();
app.use(express.static('client'));
/*
app.get('/', function (req, res) {
res.send('Hello World!');
});*/
var server = app.listen(8080, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
My file index.html is available. I already used other way to keep this like by using
app.get('/index.html', function (req, res, next) {
var options = {
root: __dirname + '/client/',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.sendFile("index.html", options, function (err) {
if (err) {
console.log(err);
res.status(err.status).end();
}
else {
console.log('Sent:', "index.html");
}
});
});
And this approach works.
You said that you were trying this URL:
http://myServer.com/index.html
But, your server is listening on port 8080, so you need to use this URL:
http://myServer.com:8080/index.html
or this:
http://myServer.com:8080
Because express.static() will automatically use index.html for the / path.
FYI, when I run your first block of code on my laptop with the proper URL, it works just fine. The browser shows me the contents of client/index.html where "client" is a sub-directory below where my app.js file is run from to start the server.

Node.js / Express / Socket.io Not working on Localhost but works by going direct file

I'm developing a multi-player HTML5 game using Node.js for an Express server and Socket.io for websockets. When I try to access the game in my browser going to the port the application is listening to, I get a blank page. However, when I access the index.html file directly (while the server is running), it works perfectly.
Note, when I say "access the file directly" I mean: file:///C:/Program%20Files/nodejs/SupermarketChallenge/public/index.html
This was fine until I wanted to test the game with my housemate who needs to access it through localhost in order to play!
Here's the relevant server code:
var express = require('express'),
//Create an express server
app = express.createServer(),
//attach socket.io to the server
supermarket = require('socket.io').listen(app);
//Configure a static directory for public files
app.configure(function() {
app.use(express.static(__dirname + '/public'));
});
//set the port to listen to
app.listen(3000);
And the client:
var socket = io.connect('http://localhost:3000');
It's because going to http://localhost:3000/ does not match any valid files from your public folder. You need a route to match this. Update your code according:
var express = require('express'),
//Create an express server
app = express.createServer(),
//attach socket.io to the server
supermarket = require('socket.io').listen(app);
//Routes
app.get('/', function(req, res) {
res.redirect('/index.html');
});
//Configure a static directory for public files
app.configure(function() {
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
//set the port to listen to
app.listen(3000);
Now your route can be altered to actually serve the content of the index.html, in which case you would replace the / route with the following:
//Routes
app.get('/', function(req, res) {
res.sendfile(__dirname + '/public/index.html');
});
const app = require("express")();
const httpServer = require("http").createServer(app);
const options = { /* ... */ };
const io = require("socket.io")(httpServer, options);
io.on("connection", socket => { /* ... */ });
httpServer.listen(3000);
// WARNING !!! app.listen(3000); will not work here, as it creates a new HTTP server

Html content is not showed in NodeJS

I'm trying to create an http server. The server is created correctly but does NOT show the html content. It works when I do it without listeners. What am I failing then?
app.js
var server = require("./server.js");
server.server3((req, res, html) => {
res.writeHead(200, {"Content-Type": "text/html"});
html.pipe(res);
res.end();
}, 3000, "./index.html");
server.js
function Server3(applyFunction, port, path) {
var fs = require("fs"),
html = fs.createReadStream(path.toString().trim()), // Create stream from path
http = require("http");
html.on("data", _ => {})
.on("end", () => { // create server when all data is ready
http.createServer(function(req, res){ // createServer method
applyFunction(req, res, html); // execute the function
}).listen(+port); // add the port
});
}
module.exports.server3 = Server3;
If you're just trying to create an HTTP server on node.js, using the express framework (npm install express --save) would simplify your life a great deal. If you place the index.html file in the same directory as app.js, you can create the server with the following 5 lines of code:
// Setup Express
const express = require("express");
const app = express();
// Use main directory to find HTML file
app.use(express.static(__dirname));
// Render index.html
app.get("/", (req, res) => res.render("index"));
// Start Server on port 3000
app.listen(3000, () => console.log('Server started on port 3000'));

Resources