I have an excel file. I want to reply excel file as a stream to the user using hapi JS reply object. I tried like this but it didn't work.
let readStream = fs.createReadStream(filePath);
reply(null,readStream.pipe());
Could anyone suggest me an approach to achieve this?
Use this code for serving file . If files are static files it prints on browser otherthan static files like pdf,excel,word these files will be downloaded .
'use strict';
const Path = require('path');
const Hapi = require('hapi');
var fs = require('fs');
const server = new Hapi.Server();
server.connection({
port: 3000,
host: 'localhost'
});
server.register(require('inert'), (err) => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/testdoc.docx',
handler: function(request, reply) {
var stream = fs.createReadStream('./testdoc.docx');
stream.on('data', function(data) {
console.log(data);
console.log('loaded part of the file');
//reply(null,data);
reply(data);
});
stream.on('end', function() {
console.log('all parts is loaded');
});
}
});
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
});
run the server node server.js and in browser run as http://localhost:3000/testdoc.docx. Hope this helps.
Related
This question already has an answer here:
Link index.html client.js and server.js
(1 answer)
Closed 10 months ago.
I am trying to write a web server application for my Frontend.
The structure is for the fronted files is :
Backend
server.js
Fronted
Index
Javascript
index.js
style.css
index.html (it is outside of Frontend folder)
The code for server.js is:
const fs = require('fs');
const port = 5000;
const server = http.createServer(function (request, response) {
fs.readFile('../Frontend/index.html', function (error, data) {
response.setHeader( "Content-Type", "text/html");
if (error) {
response.writeHead(404);
response.write('Error: File Not Found');
} else {
response.write(data);
}
response.end();
})
})
server.listen(port, function (error) {
if (error) {
console.log('Something went wrong ', error);
} else {
console.log('Server is listening on port ' + port);
}
});
When I try to access localhost:5000 the HTML code shows, but without CSS, js or images, but when I am looking in the console at the network all the files are there (index.js, style.css, the images);
You can achieve the results you want as follows:
const fs = require('fs');
const port = 5000;
const http = require('http');
const server = http.createServer( function (request, response) {
let filePath = '.'+request.url; //assumes your static files are
// placed in the root directory
if(request.url ==='/' ||request.url==='/index.html'){
filePath = './index.html';
fs.readFile(filePath, function (error, data) {
response.setHeader('Content-Type', 'text/html');;
if (error) {
response.writeHead(404);
response.write('Error: File Not Found');
}
response.end(data,'utf-8');
})
} else if(request.url==='/index.css'){
filePath = './index.css';
fs.readFile(filePath, function (error, data) {
response.setHeader('Content-Type', 'text/css');;
if (error) {
response.writeHead(404);
response.write('Error: File Not Found');
}
response.end(data,'utf-8');
})
} //maybe some additional else if for image and so on or you can improve
//this logic but anyway this code gives you the right direction
})
server.listen(port, function (error) {
if (error) {
console.log('Something went wrong ', error);
} else {
console.log('Server is listening on port ' + port);
}
});
var express = require("express");
var app = express();
var fs = require("fs");
var path = require("path");
app.use('/node_modules', express.static('node_modules'));
app.get("/", function (req,res) {
pathname = path.join(__dirname,"index.html");
fs.readFile(pathname,function (err,data) {
if(err){
throw err;
}
res.send(data);
// the res.send(data), the webpage receive the data, and download it instead of showing it as HTML webpage.
}
)
});
app.listen("3000",function () {
console.log("express server constructed");
})
I will tell you the approachs to do
fs.readFile(pathname,function (err,data) {
if(err){
throw err;
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
}
If you don't want readFile you can use this.
res.sendfile(pathname);
use
res.sendFile(pathname);
instead of
res.send(data);
Sorry guys, I'm kind of lost. How can I console.log response.statusCode when piping?
var express = require('express');
var path = require('path');
var request = require('request');
var fs = require('fs');
var app = express();
var port = 8000;
var destination = fs.createWriteStream('./downloads/google.html');
var url = "http://www.google.com/";
request(url).pipe(destination)
.on("finish", function() {
console.log("done");
console.log(response.statusCode); // <<<<<<<<<<<<<<<<<<<<<<<<<<<< this
})
.on("error", function(err){
console.log(err);
});
app.listen(port, function(){
console.log('running server on ' + port);
});
You need to catch the response event from request. It won't be in the finished event from the pipe. You should also consider catching errors before the pipe. This is where you'll catch network errors. After the pipe you'll catch file errors.
request(url)
.on('response', function(response) {
console.log(response.statusCode) // <--- Here 200
})
.on("error", function(err){
console.log("Problem reaching URL: ", err);
})
.pipe(destination)
.on("finish", function(response) {
console.log("done");
})
.on("error", function(err){
console.log("Problem writing file: ", err);
});
I am not able to add css and js file please give me a code by which i can use my css or other files
This is my code:
const http = require('http');
const fs = require('fs');
const port = 3000;
fs.readFile('index.html',(err,html) => {
if(err){
throw err;
}
const server = http.createServer((req,res) => {
res.statusCode = 200;
res.setHeader('content-type', 'text/html');
res.write(html);
res.end();
});
server.listen(port, hostname, () =>{
console.log("server started on port: "+port)
});
});
my file location is
test.js
index.html
public /css==>here my css files
/js ==>here my other js files
I am using node wget to download files from URL and I am getting this error.
If I use simple wget command to download files it working fine, but I want download file from node module
here is my code
var wget = require('wget');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, response) {
var options = {
protocol: 'https',
host: 'raw.github.com',
path: '/Fyrd/caniuse/master/data.json',
proxy: 'http://host:port',
method: 'GET'
};
var req = wget.request(options, function(res) {
var content = '';
if (res.statusCode === 200) {
res.on('error', function(err) {
console.log(err);
});
res.on('data', function(chunk) {
content += chunk;
});
res.on('end', function() {
console.log(content);
});
} else {
console.log('Server respond ' + res.statusCode);
}
});
req.end();
req.on('error', function(err) {
console.log(err);
});
response.render('index', { title: 'Express' });
});
module.exports = router;
I stumble upon this question. This is probably caused by the proxy not supporting HTTPS. Try a proxy that supports HTTPS and the problem should be solved.