javascript - Trying to respond with text split into array of words from node.js http server -
new node.js, appreciate can offer. trying response out variable 'words' when start server , go localhost crashes , says " typeerror: first argument must string or buffer" when try write same variable console works. 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 = 0; < 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;
i'd this:
… var words = text.split(/\s+/); // hardly want split on every word boundary // rather on spaces in between … var wordcounts = {}; // object, not string! (var = 0; < 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 string! …
Comments
Post a Comment