Node.js module system here… is CommonJS, but EcmaScript modules are preferably used from ver. 17.x. because EcmaScript module system supports asynchronous importation.
EcmaScript module system may be used by setting
package.json
as follows:"type": "module",
Globals like
__dirname
or__filename
are not accessible within EcmaScript module system.import {fileURLToPath} from "node:url"; import path from "node:path"; // import Image_processing from './Sharp'; // Compilation import Image_processing from './Sharp.js'; // Execution (function Main() { console.clear(); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta // '__filename' *IS NOT* defined in EcmaScript module scope: const __filename = fileURLToPath(import.meta.url); // Required: '"module": "ES2020",' console.info("Executable file: " + __filename + "\n"); // '__dirname' *IS NOT* defined in EcmaScript module scope: const __dirname = path.dirname(fileURLToPath(import.meta.url)); // Location of picture: Image_processing(path.resolve(__dirname, '..')); })();
node:assert
here… and Sharp image processing here… librariesimport {strict as assert} from 'node:assert'; // import * as Sharp from "sharp"; // It does not work... import Sharp from "sharp"; // '"allowSyntheticDefaultImports": true,' is required... const Image_processing = (image_location: string) => { try { const image = Sharp(image_location + "/Lips.png"); image.metadata().then(metadata => { assert.strictEqual(metadata.format, "png"); console.log(metadata); }); image.grayscale() .rotate(180, {background: {r: 0, g: 0, b: 0, alpha: 0}}) .toFile("Lips_.png"); } catch (error: unknown) { console.log(`An error occurred during processing: ${error}`); } } export default Image_processing;