I'm working on a Node.js app, using http and httpdispatcher to handle web server requests. I have the following code:
var app = require('http').createServer(handler),
sys = require('util'),
exec = require('child_process').exec,
io = require('socket.io').listen(app),
fs = require('fs'),
dispatcher = require('httpdispatcher');
app.listen(61337);
dispatcher.setStatic('assets');
function puts(error, stdout, stderr) { sys.puts(stdout) }
function handler (request, response) {
dispatcher.dispatch(request, response);
}
dispatcher.onGet("/", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('./assets/index.html', 'utf8', function (err,data) {
res.end(data);
});
});
dispatcher.onGet("/api/update", function(req, res) {
exec("sh /path/to/update.sh &", puts);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('1');
});
io.sockets.on('connection', function (socket) {
/** Socket.io coming soon */
});
I get the following errors.
path.js:360
throw new TypeError('Arguments to path.join must be strings');
TypeError: Arguments to path.join must be strings
at path.js:360:15
at Array.filter (native)
at Object.exports.join (path.js:358:36)
at HttpDispatcher.staticListener (***/httpdispatcher.js:81:39)
at ***/httpdispatcher.js:132:3
at HttpChain.next (***/httpdispatcher.js:125:9)
at doDispatch (***/httpdispatcher.js:58:13)
at HttpDispatcher.dispatch (***/httpdispatcher.js:74:14)
at Server.handler (***/app-server.js:19:13)
at Server.<anonymous> (***/socket.io/node_modules/engine.io/lib/server.js:369:22)
The Server.handler (***/app-server.js:19:13) line is dispatcher.dispatch(request, response); in the handler function.. so I'm not sure why it's not sending strings?
I went from using httpdispatcher to express
Here is my working example:
var express = require('express'),
app = express(),
http = require('http').createServer(app).listen(61337),
sys = require('util'),
exec = require('child_process').exec,
io = require('socket.io')(http),
fs = require('fs');
app.use('/assets', express.static('assets'));
function puts(error, stdout, stderr) { sys.puts(stdout) }
app.get("/", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
fs.readFile('./assets/index.html', 'utf8', function (err,data) {
res.end(data);
});
});
app.get("/api/update", function(req, res) {
exec("sh /path/to/update.sh &", puts);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('1');
});
io.sockets.on('connection', function (socket) {
});
Related
I'm new programmer to node.js. I trying to create vanilla server in node.js. In my client, I used ES6 modules. when I start my server and search for http://localhost:3000/ in my browser, HTML and CSS loaded but for javascript have this error:
I have four javascript modules for client side and in HTML I use this code for load javascript moduls:
<script type="module" src="js/controller.js" async></script>
My server code :
const http = require('http');
const fs = require('fs');
const path = require('path');
const PORT = 3000;
const server = http.createServer();
server.on('request', (req, res) => {
let routes = {
'GET': {
'/': indexHtml,
}
}
console.log(req.url)
let handler = routes[req.method][req.url];
handler = handler || readFile;
handler(req, res);
})
server.listen(PORT, () => {
console.log(`Listening on port ${PORT}...`)
});
function indexHtml(req, res) {
readFile({ url: '/index.html' }, res);
}
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
// console.log(filePath)
fs.readFile(filePath, (error, data) => {
if (error) {
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
res.writeHead(200);
res.write(data);
res.end();
}
})
}
How can I solve this error and serve javascript modules, Thanks a lot for your help.
With comment #derpirscher, I change my reader function with this code :
function readFile(req, res) {
var filePath = path.join(__dirname, '../client/', req.url);
fs.readFile(filePath, (error, data) => {
if (error) {
res.setHeader('Content-Type', 'text/html');
res.writeHead(404);
res.write('Not found error 404');
res.end()
} else {
const url = req.url === '/' ? '/index.html' : req.url;
if (req.url.includes('js')) res.setHeader('Content-Type', 'application/javascript');
if (req.url.includes('css')) res.setHeader('Content-Type', 'text/css');
if (req.url.includes('html')) res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write(data);
res.end();
}
})
}
var http = require("http");
var fs = require("fs");
http.createServer(function (req, res) {
fs.readFile("demo1.html", function (err, data) {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
return res.end();
});
}).listen(80);
Error :
You don't check for an error in the callback of readFile. If there is an error, data will be undefined and res.write(data) throws the error you see.
var http = require("http");
var fs = require("fs");
http.createServer(function (req, res) {
fs.readFile("demo1.html", function (err, data) {
if (err) {
console.log(err);
res.writeHead(404); //or whatever status code you want to return
} else {
res.writeHead(200, { "Content-Type": "text/html" });
res.write(data);
}
return res.end();
});
}).listen(80);
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);
I'm trying to pick up a file from a form and save it to myself on disk in any folder. I would like to do it by sockets, but I do not know how to handle it. Can someone help me?
This is my code:
main.js
var http = require('http');
var fs = require('fs');
var io = require('socket.io');
var path = require('path');
var server = http.createServer(function (req, res) {
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("Not Found");
res.end();
} else {
res.write(data, 'utf8');
res.end();
}
});
}).listen(8000);
var listener = io.listen(server);
listener.sockets.on('connection', function (socket) {
console.log("Connected");
socket.on('disconnect', function () {
console.log("Disconnect");
});
socket.on('form.message', function (data) {
// here to handle the file ??
socket.emit('new.message', {msg: data});
});
});
index.html(client)
<script>
$(function () {
var socket = io.connect();
var $messageForm = $('#messageForm');
var $file = $('#file');
var $outputFile = $('#outputFile');
var obj = {
file: $file.val(),
};
e.preventDefault();
console.log(obj);
socket.emit('form.message', obj);
$file.val('');
socket.on('new.message', function (data) {
$outputFile.append('<div class="well">' + data.msg.file + '</div>');
});
});
</script>
I have the following simple code for a nodejs server....
var http = require('http');
var port = 1337;
var dispatcher = require('httpdispatcher');
dispatcher.setStaticDirname(__dirname);
dispatcher.setStatic('');
dispatcher.onGet("/page1", function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Page One');
});
var server = http.createServer().listen(port);
server.on('request', function (req, res) {
console.log('GOT');
dispatcher.dispatch(req, res);
});
console.log('Listening on port %s', port);
when I goto http://localhost:1337/index.html it is showing up correctly but when I do http://localhost:1337/page1 nothing happens...how can I get it to function properly...
You need to define your custom dispatcher events, in this case "/page1", before setting the static dispatcher. Otherwise static hogs every possible path remaining to check against the file system.
dispatcher.onGet("/page1", function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Page One');
});
dispatcher.setStaticDirname(__dirname);
dispatcher.setStatic('');
Your revised code will look like this:
var http = require('http');
var port = 1337;
var dispatcher = require('httpdispatcher');
dispatcher.onGet("/page1", function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Page One');
});
dispatcher.setStaticDirname(__dirname);
dispatcher.setStatic('');
var server = http.createServer().listen(port);
server.on('request', function (req, res) {
console.log('GOT');
dispatcher.dispatch(req, res);
});
console.log('Listening on port %s', port);
Tested and works