如何将“代码"值捕获到变量中? [英] How to capture the 'code' value into a variable?

查看:22
本文介绍了如何将“代码"值捕获到变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码在使用 nodejs 和 ssh2 模块的 linux 机器上重置密码:

I'm using the below code to reset a password on a linux box using nodejs and ssh2 module:

// FILE * ./workflow/ssh.js

var Client = require('ssh2').Client;
var conn = new Client();

// var opts = require('optimist')
//     .options({
//         user: {
//             demand: true,
//             alias: 'u'
//         },
//     }).boolean('allow_discovery').argv;

// Definition of reset password;

var resetPassword = function(user, host, loginUser, loginPassword){

var command = 'echo -e "linuxpassword\nlinuxpassword" | passwd '+ user;

conn.on('ready', function() {
  console.log('Client :: ready');
  conn.exec(command, function(err, stream) {
    if (err) throw err;
    stream.on('close', function(code, signal) {
      console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
      conn.end();
      return(code);
    }).on('data', function(data) {
      console.log('STDOUT: ' + data);
    }).stderr.on('data', function(data) {
      console.log('STDLOG: ' + data);
    });
  });
}).connect({
  host: host,
  port: 22,
  username: loginUser,
  password: loginPassword
});
};

exports.resetPassword = resetPassword;

我正在从另一个模块调用 resetPassword 密码函数,比如下面的 test.js.

I'm calling the resetPassword password function from an other module , say test.js as below.

var ssh = require('./workflow/ssh.js');

result = ssh.resetPassword('test122', '192.168.0.101', 'root' , 'password');
console.log(result)

但是console.log 显示未定义".尝试使用 process.nextTick,但没有运气.请帮忙.

But the console.log says "undefined". Tried using the process.nextTick, but no luck. Please help.

推荐答案

欢迎来到在 node.js 中使用异步操作进行开发的世界.这是最初学习 node.js 时一个非常常见的错误(也是 StackOverflow 上的一个常见问题).异步操作会在未来某个不确定的时间完成,同时,您的其余代码会继续运行.事实上,您的 resetPassword() 函数可能会在流完成之前和 resetPassword 结果可用之前返回.

Welcome to the world of developing with asynchronous operations in node.js. This is a very common mistake when initially learning node.js (and a common question here on StackOverflow). An asynchronous operation completes some indeterminate time in the future and meanwhile, the rest of your code continues to run. In fact your resetPassword() function likely returns BEFORE the stream has finished and before the resetPassword result is available.

因此您不能直接从 resetPassword 函数返回结果,因为该函数在结果准备好之前返回.相反,您必须传入回调并在调用回调时获取结果,并且此函数的调用者必须使用回调而不是直接返回的结果.你可以这样实现:

Thus you cannot return the result from the resetPassword function directly because the function returns before the result is ready. Instead, you will have to pass in a callback and get the result when the callback is called and the caller of this function will have to use the callback rather than a directly returned result. You can implement that like this:

// FILE * ./workflow/ssh.js

var Client = require('ssh2').Client;
var conn = new Client();

// var opts = require('optimist')
//     .options({
//         user: {
//             demand: true,
//             alias: 'u'
//         },
//     }).boolean('allow_discovery').argv;

// Definition of reset password;

var resetPassword = function(user, host, loginUser, loginPassword, callback){

var command = 'echo -e "linuxpassword\nlinuxpassword" | passwd '+ user;

conn.on('ready', function() {
  console.log('Client :: ready');
  conn.exec(command, function(err, stream) {
    if (err) {
        callback(err);
        return;
    }
    stream.on('close', function(code, signal) {
      console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
      conn.end();
      callback(null, code);
    }).on('data', function(data) {
      console.log('STDOUT: ' + data);
    }).stderr.on('data', function(data) {
      console.log('STDLOG: ' + data);
    });
  });
}).connect({
  host: host,
  port: 22,
  username: loginUser,
  password: loginPassword
});
};

exports.resetPassword = resetPassword;

然后你可以像这样使用它:

And, then you can use that like this:

var ssh = require('./workflow/ssh.js');

ssh.resetPassword('test122', '192.168.0.101', 'root' , 'password', function(err, code) {
    if (!err) {
        console.log(code);
    }
});

附言从您的原始代码来看,它也不能真正帮助您从异步回调中抛出.异常只进入触发异步回调的任何 node.js 基础设施,它不会返回到您的原始代码.这就是为什么您的代码也已更改为通过回调传达错误的原因.

P.S. From your original code, it also doesn't really help you to throw from within an async callback. The exception only goes into whatever node.js infrastructure triggered the async callback, it does not get back to your original code. That's why your code has also been changed to communicate the error via the callback.

这是一个 node.js 约定,回调至少包含两个参数.第一个参数是一个错误代码,如果没有错误,它应该是 null ,如果有错误,它应该是一个适当的错误代码或错误对象.第二个参数(以及您想要的任何其他参数)然后传达一个成功的结果.遵循此约定很有用,因为它既与 node.js 在其他地方的做法一致,又与一些机械错误处理兼容,例如在修改接口以使用 Promise 时完成的操作.

It is a node.js convention that callbacks contain at least two arguments. The first argument is an error code which should be null if no error and an appropriate error code or error object if there is an error. The second argument (and any other arguments you want to have) then communicate a successful result. It is useful to follow this convention since it is both consistent with how node.js does it elsewhere and it is compatible with some mechanical error handling such as done when interfaces are modified to use promises.

这篇关于如何将“代码"值捕获到变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆