我正在构建一个使用linux密码shadow文件检查用户密码的函数。 问题是main(sync)函数在内部异步函数完成之前返回undefined,因此它总是返回undefined。
如何将主函数更改为异步,以便等待异步函数完成?
请指教。 事先提醒
阿德里安
function checkPass(a, b) {
"use strict";
var fs = require('fs');
var sha512crypt = require('sha512crypt-node');
//
var shadow = '/tmp/shadow';
var userNameCheck = a;
var passwordCheck = b;
//
var response;
fs.readFile(shadow, function (err, logData) {
if (err) throw err;
// logData is a Buffer, convert to string.
var shadowFile = logData.toString();
var shadowList = shadowFile.split('\n');
for (var line in shadowList) {
var userEntree = shadowList[line].split(":");
if (userEntree[0] === userNameCheck) {
var username = userEntree[0];
var fullShadow = userEntree[1];
//
var fullShadowSplit = userEntree[1].split('$');
//
var passwordAlgorithm = fullShadowSplit[1];
var saltShadow = fullShadowSplit[2];
var passwordShadow = fullShadowSplit[3];
//
var hash = sha512crypt.sha512crypt(passwordCheck, saltShadow)
//console.log(hash + '===' + fullShadow);
if (hash === fullShadow) {
console.log('LOG: oldPassCorrect');
//return 'oldPassCorrect';
response = 'oldPassCorrect';
return response;
break;
} else {
console.log('LOG: oldPassIncorrect');
//return 'oldPassCorrect';
response = 'oldPassIncorrect';
return response;
break;
}
}
}
});
}
console.log("Function response: " + checkPass('share', 'qwerty'));
答案 0 :(得分:0)
我在主函数中添加一个回调:
function checkPass(a, b, callback) {
"use strict";
var fs = require('fs');
var sha512crypt = require('sha512crypt-node');
//
var shadow = '/tmp/shadow';
var userNameCheck = a;
var passwordCheck = b;
//
var response;
fs.readFile(shadow, function (err, logData) {
if (err) throw err;
// logData is a Buffer, convert to string.
var shadowFile = logData.toString();
var shadowList = shadowFile.split('\n');
for (var line in shadowList) {
var userEntree = shadowList[line].split(":");
if (userEntree[0] === userNameCheck) {
var username = userEntree[0];
var fullShadow = userEntree[1];
//
var fullShadowSplit = userEntree[1].split('$');
//
var passwordAlgorithm = fullShadowSplit[1];
var saltShadow = fullShadowSplit[2];
var passwordShadow = fullShadowSplit[3];
//
var hash = sha512crypt.sha512crypt(passwordCheck, saltShadow)
//console.log(hash + '===' + fullShadow);
if (hash === fullShadow) {
console.log('LOG: oldPassCorrect');
response = 'oldPassCorrect';
callback(response);
break;
} else {
console.log('LOG: oldPassIncorrect');
response = 'oldPassIncorrect';
callback(response);
break;
}
}
}
});
}
checkPass('share', 'qwerty', function (response) {
console.log("CallBack: " + response);
});