Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
23
rated 0 times [  29] [ 6]  / answers: 1 / hits: 19518  / 7 Years ago, fri, june 23, 2017, 12:00:00

Using this answer, with mkdirp, I want to create a directory and save files inside. Inside of plates those folders will be created and reuse if present.



const fs = require('fs')
const mkdirp = require('mkdirp')

// Decode image then save to local storage
const decodeBase64Image = (string, plateNumber) => {
let regex = /^data:.+/(.+);base64,(.*)$/
let matches = string.match(regex)
let ext = matches[1]
let data = matches[2]
let buffer = new Buffer(data, 'base64') // I cant use Buffer.alloc()

let pathForImages = `plates/${plateNumber}`

saveImagesToPath(pathForImages, ext, buffer)
}


const saveImagesToPath = (pathForImages, ext, buffer) => {
mkdirp(pathForImages, function (err) {

fs.writeFileSync(pathForImages, 'data.' + ext, buffer)

})
}

let string = data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/<SHORTEN>w==

// Performing it all
decodeBase64Image(string, 'HGT5KU')


Error message:



fs.js:651
return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
^

Error: EISDIR: illegal operation on a directory, open 'plates/HGT5KU'


Basically, create a sub-folder for plates with the name of the plate numbers and save data inside that folder: plates/HGT5KU/foo.png others: plates/GFTYU7/bar.jpg


More From » node.js

 Answers
32

You're telling fs.writeFileSync to write to the directory, not to a file within the directory:



mkdirp(pathForImages, function (err) {
fs.writeFileSync(pathForImages, 'data.' + ext, buffer)
// ----------------^^^^^^^^^^^^
})


Of course that's going to fail. You need to add a filename to the path:



mkdirp(pathForImages, function (err) {
const filename = /*...create appropriate filename...*/;
fs.writeFileSync(pathForImages + / + filename, 'data.' + ext, buffer)
})





Side notes:




  1. It's not generally good practice to ignore errors. mkdirp can fail, you need to check err.


  2. Since mkdirp is asynchronous, using a synchronous call within it is pointless and unnecessarily ties up the JavaScript thread. Just use writeFile. In general, avoid xyzSync functions without a really good reason to use them.


  3. Proabably best to test for errors from writeFileSync/writeFile, too. :-)



[#57329] Wednesday, June 21, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
manuel

Total Points: 747
Total Questions: 96
Total Answers: 95

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;