Skip to content

Commit

Permalink
added error checking for watcher and file reader
Browse files Browse the repository at this point in the history
  • Loading branch information
underdorff18 committed Nov 20, 2022
1 parent 2825f14 commit ef2c00e
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 9 deletions.
Binary file modified JS/1234.xlsx
Binary file not shown.
59 changes: 50 additions & 9 deletions JS/excelreader.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,37 +10,78 @@ const { all } = require('express/lib/application');
//const myfilepath = Path.join(__dirname, 'Inventory', 'samplepc1234.xlsx');

function readInventoryFile(filepath) {
//Checking for correct file type
const fileinfo = Path.parse(filepath);
if (fileinfo.ext !== ".xlsx") {
return {error: "Given file is not xlsx format"}
}

let workbook = xlsx.readFileSync(filepath);
let sheetNames = workbook.SheetNames;
let sheetData = workbook.Sheets[sheetNames[0]];

let system;

//Here is where we use known cell locations of the specs needed to build the systems file
let serialnum = sheetData.D1.v;
let model = sheetData.D2.v;
let OS = sheetData.D3.v;
let price = sheetData.D4.v;
let specs = [sheetData.D5.v, sheetData.D6.v, sheetData.D7.v, sheetData.D8.v];
try {
system = new System(
sheetData.D1.v,
sheetData.D2.v,
sheetData.D3.v,
sheetData.D4.v,
[sheetData.D5.v, sheetData.D6.v, sheetData.D7.v, sheetData.D8.v]);
}
catch (error) {
console.error(error);
}

//Checking if file is formatted correctly
if (!system) {
return {error: "One or more necessary values are not defined"}
}
if (parseInt(fileinfo.name) !== system.serialnum) {
return {error: "filename does not match serial number"};
}

return new System(serialnum, model, OS, price, specs);
return system;
}


var inventoryWatcher = chokidar.watch(Path.join(__dirname, "Inventory"), {
ignored: /(^|[\/\\])\../,
persistent: true,
awaitWriteFinish: true,
ignoreInitial: true
});
console.log(`Watching directory for changes...` )

inventoryWatcher
.on('add', function(filepath) {
dbtools.insertSystem(readInventoryFile(filepath));
const system = readInventoryFile(filepath);
if (system.error) {
console.error(system.error);
}
else {
dbtools.insertSystem(system);
}

})
.on('change', function(filepath) {
dbtools.updateSystem(readInventoryFile(filepath));
const system = readInventoryFile(filepath);
if (system.error) {
console.error(system.error);
}
else {
dbtools.updateSystem(system);
}
})
.on('unlink', function(filepath) {
dbtools.deleteSystem(parseInt(Path.basename(filepath, '.xlsx')));
if (Path.extname(filepath) !== ".xlsx") {
console.log("inventoryWatcher: a non xlsx file has been deleted");
}
else {
dbtools.deleteSystem(parseInt(Path.basename(filepath, '.xlsx')));
}
})
.on('error', function(error) {
console.error('Error happened', error);
Expand Down

0 comments on commit ef2c00e

Please sign in to comment.