New to node.js, appreciate all the help you can offer. Trying to response out the variable 'words' but when I start the server and go to localhost it crashes and says " TypeError: first argument must be a string or Buffer" but when I try to write the same variable to the console it works. Thanks for the help!
var http = require("http");
var fs = require('fs');
var text = fs.readFileSync("text.txt").toString();
var words = text.split(/\b/);
function start(){
function onRequest(request, response){
response.writeHead(200, {"Content-type": "text/plain"});
var wordCounts = '';
for(var i = 0; i < words.length; i++)
wordCounts["_" + words[i]] = (wordCounts["_" + words[i]] || 0) + 1;
response.write(words);
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("server has started");
}
exports.start = start;
The console will have no problem with this, because it will automatically stringify most anything you put into console.log(). Try this: response.write(JSON.stringify(words))
I'd do it like this:
…
var words = text.split(/\s+/); // you hardly want to split on every word boundary
// but rather on the spaces in between
…
var wordCounts = {}; // an object, not a string!
for (var i = 0; i < words.length; i++)
wordCounts["_" + words[i]] = (wordCounts["_" + words[i]] || 0) + 1;
var result = Object.keys(wordCounts).sort(function(a, b) {
return wordCounts[b]-wordCounts[a];
}).map(function(w) {
return w.slice(1)+": "+wordCounts[w];
}).join("\n");
response.write(result); // write a string!
…