I have a simple application running on node.js with websockets. This application uses the node-static module for serving some html pages with css, js and so on.
The folder structure is this:
-app
- index.html
- server.js
- img/
- base.png
- sub/
- sub.png
- scripts
- base.js
- sub/
- sub.js
- css
- base.css
- sub/
- sub.css
Where server.js is the server file. Inside server.js there is the following code:
var static = require('node-static');
var http = require('http');
var file = new(static.Server)();
var app = http.createServer(function (req, res) {
file.serve(req, res);
}).listen(process.env.PORT || 1234);
var WebSocketServer = require('websocket').server;
new WebSocketServer({
httpServer: app,
autoAcceptConnections: false
}).on('request', onRequest);
...
Now I need to switch from node-static to Express because I need to use routes. I used this code, however it doesn't work:
var express = require('express');
var app = express();
var http = require('http');
var httpServer = http.Server(app);
app.use(express.static(__dirname+'/app'));
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
app.listen(1234);
var WebSocketServer = require('websocket').server;
new WebSocketServer({
httpServer: app,
autoAcceptConnections: false
}).on('request', onRequest);
...
I can serve files, however it breaks the websocket connection.
What's wrong? Please note that the solution should be suitable for working on localhost and Heroku.
I resolved my problem using the following code:
var http = require("http");
var express = require("express");
var app = express();
var port = process.env.PORT || 1234;
app.use(express.static(__dirname + "/"));
var server = http.createServer(app);
server.listen(port);
console.log("http server listening on %d", port);
var WebSocketServer = require('websocket').server;
new WebSocketServer({
httpServer: server,
autoAcceptConnections: false
}).on('request', onRequest);
...
This code is derived from https://devcenter.heroku.com/articles/node-websockets, however my code use the 'websocket' node module instead of 'ws'. Thanks to #Tony for the hint.
Related
How can i get all connected peers if i have simple server:
var port = 9000;
var express = require('express');
var app = express();
var ExpressPeerServer = require('peer').ExpressPeerServer;
app.get('/', function(req,res){
res.send('server OK');
//console.log(ip.address());
});
var server = require('http').createServer(app);
app.use('/peerjs',ExpressPeerServer(server));
server.listen(port,'0.0.0.0');
and client:
var peer = new Peer(
{host:"hostname",
port:9000,path:"/peerjs",
debug:3,
config:servers,
});
i use peerjs lib. Thank in advance!
Peer.js has method listAllPeersĀ on the client side. And you can use it if you add allow_discovery: true parameter in options on the server side.
This should help you
I have the below code for a file server and I would like to use and html page to show an index of the files that are available for download in the static folder "public1"
I currently can serve an html page if the user explicitly requests it but I can't make it automatically serve the html page. The commented out code is my attempt at serving the html page named "hello" by default. It doesn't work...
How can I make the html page display (by default) to the user that navigates to the ip address in a browser?
How can I make the html file show an index of files in the static folder?
So for this two part question, does anyone know how to do this? Can you point me in the right direction.
var express = require('express');
var server = express();
var port = 10001;
//server.get(__dirname + 'public1', function(req, res) {
// res.send('Hello.html');
//});
server.use(express.static(__dirname + '/public1'));
server.listen(port, function() {
console.log('server listening on port ' + port);
});
The easiest way to do this is by using the serve-index and serve-static middleware that is available for express. The below example code works, just swap out the process.cwd() for whatever directory you'd like to serve.
const express = require('express');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
const path = require('path');
const server = express();
const port = process.env.PORT || 3000;
function setHeaders(res, filepath) {
res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath));
}
const dirToServe = process.cwd();
server.use('/', serveIndex(dirToServe, {icons: true}));
server.use('/', serveStatic(dirToServe, {setHeaders: setHeaders}));
server.listen(port, () => {
console.log('listening on port ' + port);
});
I am learning node.js where i am trying to use Google webpage to work on my localhost where its menu items to be removed but its search functionality should work on localhost as it works on website. This I tried working to use google on localhost but on localhost it shows "Can not Get", is this a kind of error or am i doing wrong please guide me that how i can achieve what i want to work. I am using node.js ver5.9.1 on XP.
Thanks in advance.
search.js
var express = require('express'),
app = express();
var bodyParser = require('body-parser');
compression = require('compression');
var NLTunnel = require('node-local-tunnel');
var options = {
remoteHost : 'http://www.google.com/',
localBase : 'http://localhost:3000'
};
NLTunnel.client(options);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(compression());
app.use(express.static('assets/'));
app.listen(3000);
var express = require('express'),
app = express(),
bodyParser = require('body-parser'),
compression = require('compression'),
http = require('http'),
server = http.createServer(app);
app.use(bodyParser());
app.use('/', express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(compression());
server.listen(3000);
Try this. This is working on my machine.
I have tried using request and cheerio but i am getting only html page and no any css or js page (if there) and search function is also not working. Is this right to work on and how we can make search functionality to work as usual on localhost.
var httpobj = require('http');
var request = require('request');
var cheerio = require('cheerio');
var all_html;
var url = 'https://www.google.co.in/?gfe_rd=cr&ei=dVHeVuLuG-uK8QeCk6vICw'
request(url, function (error, response, html) {
var $page = cheerio.load(html);
all_html = $page("html");
});
httpobj.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(all_html + ' ');
res.end('');
}).listen(8124, "127.0.0.1");
console.log('Server running at http://127.0.0.1:8124/');
I'm having a node app which needs to get some zip file from client Postman and extract it to a folder in my fileSystem,Im using express I did the following which doesnt work,
what am I missing here?
I've created sample node app to simulate the issue.
var express = require('express');
var upload = require('multer')({ dest: 'uploads/' });
var admZip = require('adm-zip');
var app = express();
app.post('/',upload.single('file'),function(req,res){
debugger;
var zip = new admZip(req.file);
zip.extractAllTo("C://TestFolder//TestPathtoExtract", true);
res.send("unzip");
});
var server = app.listen(3001,function(){
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
})
This is how I use it im postman
If there is other way to do it with different open source this can be great!
I use
https://github.com/cthackers/adm-zip
which can be change to any other library
I've also find this lib but not sure how to use it with express
https://www.npmjs.com/package/decompress-zip
Thanks!
This is the set up I did for Postman, first this is my form-data body
Now in the header I left in blank after trying to set multipart/form-data manually and utterly failed, so no header here.
Here I did a pair of console.log, one of req.headers to be sure of Postman sending the right multipart/form-data and another of req.file
And well the output seems to be fine
Edit: the code.
var express = require('express');
var upload = require('multer')({
dest: 'uploads/'
});
var admZip = require('adm-zip');
var app = express();
app.post('/', upload.single('file'), function(req, res) {
console.log('%c > req.headers test.js [9] <=================================', 'color:blue;', req.headers);
debugger;
console.log('%c > req.file test.js [10] <=================================', 'color:blue;', req.file);
//instead of just req.file I use req.file.path as admzip needs the actual file path
var zip = new admZip(req.file.path);
zip.extractAllTo("/Users/myuser/Desktop/ext", true);
res.send("unzip");
});
var server = app.listen(3001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You need to pass filename as argument.
Use req.file.path
var zip = new admZip(req.file.path);
I have this piece of code on my server
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
io.sockets.on('connection', function (socket) {
console.log("Socket connected");
});
I just want to create a connection
and on the client -
<script src="public/javascripts/socket.io.js"></script>
<script>
var socket = io.connect('http://127.0.0.1:3000');
</script>
And when I open my browser I get this error in console:
GET http://127.0.0.1:3000/socket.io/1/?t=1404410309733 400 (Bad Request) socket.io.js:1659
XHR finished loading: GET "http://127.0.0.1:3000/socket.io/1/?t=1404410309733".
I've already done this like 10 times and I never get this. Does anyone know how to fix it?
I think an older version of socket-io could be the reason.
I was getting this problem when I was using 0.9.16 version. I upgraded to following and it worked.
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>