1

I'm uploading my file using multer, and then I'm trying to read the JSON file and do some operations for it. Apparently, when I take the name of the file and pass it to my function I'm getting the error following error: enter image description here

The code inside my app.js

//UPLOAD FILE READER
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'points')
  },
  filename: (req, file, cb) => {
    const { originalname } = file;
    cb(null, originalname)
  }
})

const upload  = multer ({ storage })

//Function to get the name of the file for future use
var splitTest = function (str) {
  return str.split('\\').pop().split('/').pop();
}


app.post("/uploadFile",upload.single('fileupload'),(req, res, next) => {
    // Read File Before Uploading
    const absolutePath = path.join(__dirname, req.file.path);
    const jsonString = fs.readFileSync(absolutePath, "utf-8");
    const jsonObject = JSON.parse(jsonString);
    nameFile = splitTest(absolutePath)

    //JSON SCHEMA VALIDATOR
    var innerSchema = schemas.jsonSchema;
    var innerArraySchema = {
      "type": "array",
      "items" : innerSchema
      }
    const ajv = new Ajv()
    const valid = ajv.validate(innerArraySchema, jsonObject)
    if (!valid) {
      fs.unlinkSync(req.file.path)
      res.redirect('admin')
    }
    else {
    console.log(nameFile)
    rFile(nameFile)
    res.redirect('admin')
    }
})

Also the function I call inside my app.js.

//Load JSON DATA to MySQL
rFile("starting_pois.json") --> For testing its working perfectly
function rFile(fileName) {
  fs.readFile(`../points/${fileName}`, 'utf-8', (err, jsonString) => {
  // Do stuff....
Masoud
  • 375
  • 1
  • 5
  • 16
Strike
  • 77
  • 1
  • 7
  • 1
    change `fs.readFile(\`../points/${fileName}\`` => `fs.readFile(\`./points/${fileName}\``. or simply pass `jsonString`... – traynor Jul 28 '22 at 18:09
  • also instead of `splitTest` check: https://stackoverflow.com/questions/19811541/get-file-name-from-absolute-path-in-nodejs – traynor Jul 28 '22 at 18:12
  • @traynor thanks for the reply I will check it tomorrow after work. I will mark it if its working – Strike Jul 28 '22 at 20:33
  • @traynor worked perfectly upvote your comment. + splitTest I used the path.basename. One last question if i use nodemon my server will restart when i upload the file before reaching the function rFile (To bulk-insert the data in my db). I used just node but is there a way to avoid that? I tried forever but my app was restarting 3 times and stopped everytime – Strike Jul 29 '22 at 15:06
  • 1
    so try making nodemon ignore that folder, which is probably why it's restarting.. – traynor Jul 29 '22 at 17:51

0 Answers0