我已经阅读并听说过我不应该在函数中返回值,因为它是一个阻塞操作,并且在操作完成之前它可能会拒绝任何请求。
所以这是我编写的一个小函数,我想知道我是否正确处理它。我这样说是因为我刚开始使用节点而且我想以正确的方式编码,也因为在函数内部有一个测试条件而另一个测试回调感觉很奇怪。
function isWithinSplit(path, target, separator, callBack)
{
var response = "";
var readStream = fs.createReadStream(path);
readStream.on('data', function (data) {
response += data;
});
//Data complete, process it
readStream.on('end', function (close)
{
var array = response.split(separator);
for (var idx=0 ; idx < array.length; idx++)
{
if(array[idx] != "" && array[idx] == target)
callBack("true");
else
callBack("false");
}
});
}
致电:
fileHelper.isWithinSplit(__dirname + ROOM_LIST_PATH, "hello", "|", function(data){
if(data == "true")
console.log("hurray!");
});
我只是想知道这是人们如何做以及它是否有效。
答案 0 :(得分:3)
你忘记了
===
function isWithinSplit(path, target, separator, callBack) {
var response = "";
var readStream = fs.createReadStream(path);
readStream.on('data', function _aggregateData(data) {
response += data;
});
//Data complete, process it
readStream.on('end', function _findTarget(close) {
var array = response.split(separator);
for (var idx = 0, len = array.length; idx < len; idx++) {
if (array[idx] === target) {
return callBack(null, true);
}
}
callback(null, false);
});
readStream.on('error', callBack);
}
fileHelper.isWithinSplit(__dirname + ROOM_LIST_PATH, "hello", "|", printIfSuccess);
function printIfSuccess(err, data) {
if (data === true) {
console.log("hurray!");
}
}
您还可以使用Array.prototype.any
readStream.on('end', function(close) {
callback(null, response.split(seperator).any(function _doesItMatchTarget(val) {
return val === target;
}));
});