带有参数的模块 NodeJS

Modules with Arguments NodeJS

本文关键字:模块 NodeJS 参数      更新时间:2023-09-26

我有两个文件,home.js和module.js在同一个目录中。我正在尝试做的是,当我调用从 module.js 导出的函数时,我正在尝试传递名为 directory 的变量。

它给了我这个错误:binding.readdir(pathModule._makeLong(path(, req(;类型错误:路径必须是字符串。

我想弄清楚的是,我已经从家里传递了目录变量 process.argv[2](包含路径.js因为我在模块中调用函数.js需要相同的参数(路径(。

首页.js

var fs = require('fs');
var path = require('path');
var module = require('./module.js');
var directory = process.argv[2];
var extensionRequired = process.argv[3];
function printList(err, data) {
    if(err) return err;
    list.forEach(function (file) {
        if(path.extname(file) === '.' + extensionRequired) {
            console.log(file);
        }
    });
}
module(directory, extensionRequired, printList);

模块.js

var fs = require('fs');
var path = require('path');
module.exports = function (directory, extensionRequired, callBack) {
    fs.readdir(directory, function(err, list) {
        if(err) return err;
        callBack(err, list)
    });
}

我认为你犯了一个错误,忘记重命名list变量:

function printList(err, data) {
    if(err) return err;
    // Here list => data
    data.forEach(function (file) {
        if(path.extname(file) === '.' + extensionRequired) {
            console.log(file);
        }
    });
}

在名为 printList 的回调方法中,将第二个参数设置为 data 。如果要再次访问第二个参数的值,则必须在代码中使用data或将其重新分配给另一个变量。

然后,您的方法可能如下所示:

function printList(err, data) {
  if (err) return err;
  data.forEach(function (file) {
    if(path.extname(file) === '.' + extensionRequired) {
        console.log(file);
    }
  });
}

此外,我看到您的代码还有两个问题:

  1. module.js 中,您需要参数 extensionRequired 。如果你仔细观察,你会发现,它甚至没有在这种方法中使用。这不是一个真正的错误,但在我看来会被视为不优雅。而是将其作为附加参数传递给printList(恕我直言,更多的是节点典型方式(,或者像您当前所做的那样将其用作全局范围变量。

  2. module.jsmodule.exports 匿名函数中,您正在使用 if (err) return err; 。我强烈建议你不要做这样的事情。因为这是一个异步方法,所以你不能真正返回一些东西,因为 return-语句实际上可能会在你调用此方法后执行。相反,将错误作为回调的第一个参数传递。如果没有错误,请改为传递null,以便您可以轻松确定是否发生了意外情况。总是检查一下!

然后,您的module.js可能如下所示:

var fs = require('fs');
var path = require('path');
module.exports = function (directory, callback) {
  fs.readdir(directory, function(err, list) {
    if (err)
      // Error happened, pass it to the callback 
      callback(err);
    else 
      // Everything ran smooth, send null as the error (no error)
      // and the list as the second argument.
      callback(null, list)
  });
}

然后,应相应地更改您的home.js

var fs = require('fs');
var path = require('path');
var module = require('./module.js');
var directory = process.argv[2];
var extensionRequired = process.argv[3];
function printList(err, data) {
  if (err) {
    console.error("An error occurred:", err);
    // Exit with an error-code of one to 
    // tell failure to the calling process and
    // prevent printing the probably 'undefined' data-variable
    process.exit(1);
  }
  data.forEach(function (file) {
    if(path.extname(file) === '.' + extensionRequired) {
      console.log(file);
    }
  });
}
// extensionRequired removed, as it is not needed
module(directory, printList);