node.js新手,感谢您提供的所有帮助。 尝试响应变量'words',但是当我启动服务器并转到localhost时它会崩溃并说“TypeError:first argument必须是一个字符串或Buffer”,但是当我尝试将相同的变量写入控制台时,它可以工作。 谢谢您的帮助!

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;

===============>>#1 票数:1

控制台没有任何问题,因为它会自动将您放入console.log()大部分内容字符串化。 试试这个: response.write(JSON.stringify(words))

===============>>#2 票数:1 已采纳

我这样做:

…
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!
…

  ask by Santiago Moreno translate from so

未解决问题?本站智能推荐: