0

I've been trying for 1 week without success to render the psd conversion through this nodejs module: https://www.npmjs.com/package/psd trying to make a confirmation message appear after converting all the images. I don't know if the problem can be traced to my code or promise compliance, I've tried like 50 times to change every aspect of this code.

In psdconverter.js file

//! PSD COMPONENT MODULES
var PSD = require('psd');
//! file and extension MODULES
const fs = require('fs');
var path = require('path');


const PSDconverter = async (filename) => {
  return new Promise((resolve, reject) => {
    PSD.open('./img/' + filename).then(function (psd) {
      let newfilename = filename.replace(/.psd/i, ""); //REPLACE CASE INSENSITIVE
      psd.image.saveAsPng('./img/' + newfilename + '.png');
      return newfilename;
    }).then(function (res) {
      console.log('PSD Conversion Finished!' + res);
      resolve(res);
    }).catch(function (err) {
      console.log(err);
    });
  })
}


const EnumAndConvert = async () => {
  return new Promise((resolve, reject) => {
    //! READ DIR IMAGE AND CONVERTION PART
    fs.readdir('./img/', (err, files) => {
      if (err)
        console.log(err + ' errore di conversione, non è stata trovata la cartella img!');
      else {
        for (let filename of files){
          var ext = path.extname('./img/' + filename);
          if (ext === '.PSD' || ext === '.psd')
          await PSDconverter(filename);
        }

      }
    })
    resolve("Everything is converted successfully");   

  })
  
}
exports.PSDconverter = PSDconverter;
exports.EnumAndConvert = EnumAndConvert;

in index.js file

function PSDconverter() {
  //! convertitore PSD
  let EnumPSDAndConvert = require('./psdconverter.js');
  EnumPSDAndConvert.EnumAndConvert().then((res) => {  //dopo che è ritornata la Promise risolta continuo
    console.log(res+"ciao");
  })
}

ERROR RESULT: await PSDconverter(filename); ^^^^^

SyntaxError: await is only valid in async function

When i want the first to be the last one. Thank you for every help!

0daycode
  • 11
  • 3
  • 2
    [Your `PSDconverter` function doesn't `return` a promise](https://stackoverflow.com/a/25756564/1048572), and [you cannot use `forEach` with an asynchronous callback](https://stackoverflow.com/a/37576787/1048572). – Bergi May 11 '21 at 15:57
  • @Bergi i've tryied right now to edit my code with your suggestion but it doesn't work. Can you post your solution please? – 0daycode May 11 '21 at 16:19
  • Can you [edit] your question to show us what you changed, please? – Bergi May 11 '21 at 16:38
  • Edited, but it gets an error although it seems all setted for the async call. – 0daycode May 12 '21 at 00:08
  • Your `PSDConverter` function looks better now, but it should avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it). Regarding the `await`, make a separate function that calls `fs.readDir` and returns a promise, then call that with `await` in `EnumAndConvert`, followed by the loop, so tht the `await PSDconverter(filename);` is not inside the `new Promise` executor callback (which is not `async`, and should not be). – Bergi May 12 '21 at 00:10
  • To explain: `async` is syntactic sugar for functions, and lets you _write_ a function with w normal `return` statement, while _actually_ returning a Promise that resolves with that data instead. `async function test() { return 4; }` and `function test() { return new Promise(resolve => resolve(4)); }` are exactly the same function. As such, either use `async`, or return a Promise, but never do both because then you're returning a promise that resolves _to a promise_, which is pretty useless =) – Mike 'Pomax' Kamermans May 12 '21 at 00:20
  • @Mike'Pomax'Kamermans & Bergi Thank you so much for these tips. I'm really grateful for all this. i'm studying the problem and i'll study deeply the solution (as soon as I find it XD) – 0daycode May 12 '21 at 00:48

1 Answers1

1

Ok the solution is: index.js

function PSDconverter() {
  //! convertitore PSD
  let EnumPSDAndConvert = require('./psdconverter.js');
  EnumPSDAndConvert.EnumAndConvert().then(() => { 
    console.log("Conversion Completed");
  })
}

psdconverter.js

//! PSD COMPONENT MODULES
var PSD = require('psd');
//! file and extension MODULES
const fs = require('fs');
var path = require('path');


const PSDconverter = (filename) => {  //without async 
  return PSD.open('./img/' + filename).then(function (psd) {
    let newfilename = filename.replace(/.psd/i, ""); //REPLACE CASE INSENSITIVE
    psd.image.saveAsPng('./img/' + newfilename + '.png');
    return newfilename;
  }).then(function (res) {
    console.log('PSD Conversion Finished!' + res);
  }).catch(function (err) {
    console.log(err);
  });
}

function readImgDir() {
  return new Promise((resolve, reject) => {
    fs.readdir('./img/', (err, files) => {
      if (err)
        console.log(err + ' errore di conversione, non è stata trovata la cartella img!');
      else {
        resolve(files);
      }
    })
    
  })
}
const EnumAndConvert = async () => {
  var files = await readImgDir();   //! READ DIR IMAGE AND CONVERTION PART
  for (let filename of files) {
    var ext = path.extname('./img/' + filename);
    if (ext === '.PSD' || ext === '.psd')
      await PSDconverter(filename);
  }

}
exports.PSDconverter = PSDconverter;
exports.EnumAndConvert = EnumAndConvert;

If there are any suggestions on how to improve the code I would be curious. Thanks Again

0daycode
  • 11
  • 3
  • This looks good! You might want to call `reject` in `readImgDir` in the error case, though. – Bergi May 12 '21 at 01:19