我是一名命令行程序员,正在编写一个程序,使用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的新手,欢迎任何帮助。谢谢。
node orderPrice.js --list "P4 6 P10 5 P12 1"
。 - eskawlnode orderPrice.js --list Catalog.txt
就可以了。 - eskawlsample.catalog.csv
进行简单的计算 :( @eskawl - RCohen