0

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

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;
4

2 回答 2

1

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

于 2013-04-18T00:26:21.677 回答
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!
…
于 2013-04-18T01:00:24.823 回答