Node.js TypeError: 路径必须是一个字符串或缓冲区。

6
我是一名命令行程序员,正在编写一个程序,使用CSV文件中的信息计算订单的总价格。 样例.catalog.csv文件中的数据::
P1,5,1000.00
P2,8,250.00
P3,15,125.00
P4,10,250.00
P5,2,2500.00

这个程序必须从命令行运行,并带有以下参数:

例如:$ CalculateOrder sample.catalog.csv P1 2 P2 4

(P4 6 P10 5 P12 1 是来自 csv 文件的产品和数量)

总计:4151.25

目前我有以下内容:

var program = require('commander');
const csv = require('csv');
const fs = require('fs');


program
    .version('1.0.0')
    .option('-l, --list [list]', 'list of order prices in sample.catalog.csv')
    .parse(process.argv)

console.log("hello world")
console.log("list of order prices", program.list);


/* 
    To read csv file and print the data to the console:
    [node orderPrice --list input/sample.catalog.csv]
*/

let parse = csv.parse;
let stream = fs.createReadStream(program.list)
    .pipe(parse({ delimiter: ',' }));

var total = 0;
const vat = 23;
const totalWithVat = total * vat;

stream
.on('data', function (data) {
    let product = data[0];
    let quantity = data[1];
    let price = data[2];
    console.log(product, quantity, price);
    calculateOrder = () => {
        if (quantity > 20) {
            stream.destroy(new Error("Quantity exceeds stored amounts"));
        }
        total += price * quantity;
    }
})

.on("finish", function () {
    console.log("Total price:", totalWithVat);
})

.on("error", function (error) {
    console.error("The following error occured:", error);
})

我遇到了以下错误:

λ node orderPrice calculateOrder sample.catalog.csv P1 2 P2 4
hello world
list of order prices undefined
fs.js:636
binding.open(pathModule._makeLong(path),
      ^

TypeError: path must be a string or Buffer
    at Object.fs.open (fs.js:636:11)
    at ReadStream.open (fs.js:1982:6)
    at new ReadStream (fs.js:1969:10)
    at Object.fs.createReadStream (fs.js:1923:10)
    at Object.<anonymous> (E:\order-price\orderPrice.js:31:17)
    at Module._compile (module.js:643:30)
    at Object.Module._extensions..js (module.js:654:10)
    at Module.load (module.js:556:32)
    at tryModuleLoad (module.js:499:12)
    at Function.Module._load (module.js:491:3)

我是一个Node.js的新手,欢迎任何帮助。谢谢。


你在问题中提到的orderPrice是什么? - eskawl
orderPrice是我的主文件:orderPrice.js @eskawl - RCohen
所以你应该执行 node orderPrice.js --list "P4 6 P10 5 P12 1" - eskawl
λ node orderPrice.js --list P1 2 P2 4 你好世界 订单价格列表 P1 events.js:183 throw er; // 未处理的 'error' 事件 ^错误: ENOENT: 没有这样的文件或目录,打开 'E:\order-price\P1' @eskawl - RCohen
哦!我看到你正在尝试读取一个文件。在这种情况下,node orderPrice.js --list Catalog.txt 就可以了。 - eskawl
其实我只想用 sample.catalog.csv 进行简单的计算 :( @eskawl - RCohen
3个回答

2

换行

let stream = fs.createReadStream(program.list)

to

let stream = fs.createReadStream(program.argv[some number])

其中的某个数字是你提到文件名的位置。

例如,使用以下命令运行程序:

node test.js somevar filename

那么somenumber = 3

0th param > node
1st param > test.js (file to run)
2nd > somevar
3rd > filename

另一个错误:

最终代码将如下所示

const csv = require('fast-csv');
const fs = require('fs');

console.log("hello world")
console.log("list of order prices", process.argv[2]);
let required_products=[]
for(var i=3;i<process.argv.length;){
   let temp=[]
   temp.name=process.argv[i++]
   temp.quantity=process.argv[i++]
   required_products.push(temp)
}
/*
    To read csv file and print the data to the console:
    [node orderPrice --list input/sample.catalog.csv]
*/

let stream = fs.createReadStream(process.argv[2]);

var total = 0;
var csvStream = csv()
    .on("data", function(data){
         let product_name = data[0];
         let quantity = data[1];
         let price = data[2];

         required_products.forEach(function(product){

             if(product['name']==product_name){
               if(parseInt(product['quantity'])>parseInt(quantity)){
                 console.log('Quantity required for product '+product['name']+' '+product['quantity']+' is greater than available '+quantity);
                 process.exit(1)
               }else{
                 total += parseInt(price) * parseInt(product['quantity']);
               }
             }
         })
    })
    .on("end", function(){
         console.log("done");
         let totalWithVat = total * (1+ 0.23);
         console.log("Total price:", totalWithVat);
    }).on("error", function (error) {
        console.error("The following error occured:", error);
    })
 stream.pipe(csvStream);

抱歉,我不理解你的解释。另外,你有检查它是否计算正确吗?@Shubham - RCohen
现在检查一下,您是否能理解 @RCohen。 - Shubham
那么,在我的情况下是这样的吗?node orderPrice.js 3 sample.catalog.csv - RCohen
我还有点困惑。我需要计算价格,对于命令 node orderPrice -l sample.catalog.csv P1 2 P2 4 运行计算,我需要您建议的代码。正确吗?@Shubham - RCohen
为什么你在这里提到了p1 2 p2 4?它应该在CSV文件中。 - Shubham
让我们在聊天中继续这个讨论 - RCohen

1
它可能听起来很轻率,但program.list未定义,因此您无法从中读取。它未定义,因为您尚未设置commander以了解它如何从命令行映射。如果您查看commander文档中的示例,可能会提供更多信息(并查看“可变参数”的帮助)。您可以按照此示例使用命令和操作方法。
我建议,如果您刚开始,请不要使用像commander这样的软件包,除非您确实需要。您的问题实际上是关于如何使用commander。这个问题提供了一些关于如何访问命令行参数的提示。

好的,那么为什么当我执行 node orderPrice --list sample.catalog.csv 时,console.log("list of order prices", program.list); 能够正常工作呢?@Micromuncher - RCohen
它能够工作是因为你已经将--list定义为一个选项,所以它被填充了。在你的例子中,“node orderPrice calculateOrder sample.catalog.csv P1 2 P2 4”,你没有告诉commander如何处理这些参数。如果未定义列表,你可以直接访问参数而不使用commander。这有意义吗? - Micromuncher

0

具有以下目录结构:

- .. - orderPrices.js - sample.catalog.csv

您可以执行node orderPrices.js --list sample.catalog.csv使其正常工作。

如果您的CSV文件位于其他位置。您可以使用path模块的path.resolve函数通过以下方式获取CSV文件的相对位置。

fs.createReadStream(path.resolve(__dirname, program.list)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接