node.js - reading a file and output to http -
how join these scripts 1 have done not work. think callbacks getting messed up.
with code able output text browser.
var http = require('http'); http.createserver(function (req, res) { res.writehead(200, {'content-type': 'text/plain'}); res.end('hello world\n'); }).listen(1337, '127.0.0.1'); console.log('server running @ http://127.0.0.1:1337/');
with code able read text file , log console.
fs = require('fs') fs.readfile('/etc/hosts', 'utf8', function (err,data) { if (err) { return console.log(err); } console.log(data); });
but wont work together, why????????????????? help.
var http = require('http'); http.createserver(function (req, res) { fs = require('fs') fs.readfile('/etc/hosts', 'utf8', function (err,data) { if (err) { return console.log(err); } console.log(data); res.writehead(200, {'content-type': 'text/plain'}); res.end('hello world\n'); }); }).listen(1337, '127.0.0.1'); console.log('server running @ http://127.0.0.1:1337/');
you need return response after readfile
finishes. writing response in completion callback of readfile
e.g.
http.createserver(function (req, res) { fs.readfile('/etc/hosts', 'utf8', function (err,data) { if (err) { return console.log(err); } console.log(data); res.writehead(200, {'content-type': 'text/plain'}); res.end(data); }); }).listen(1337, '127.0.0.1');
Comments
Post a Comment