Error when i try to convert file using imagemagick - node.js

I try to make a PDF file cover in JPG for this I use Node JS and the following libraries ImageMagick Graphicsmagick and Ghostcript.
Code:
root/controller/convertorController.js
const path = require('path');
const {exec} = require('child_process')
let baseDir = path.join(__dirname,'../tmp');
exports.customExecution = async(req,res,next)=>{
console.log(testDir)
exec(`magick convert ${testDir} -quality 100 awbtest.jpg`,(err,stdout,stderr)=>{
if(err){
console.log(err)
}else{
console.log('success')
next();
}
})
}
Project Structure
I checked the file path is correct if when I execute the function does nothing:
Error: Command failed: magick convert D:\Project\pdf-jpg convertor\tmp/test.pdf -quality 100 awbtest.jpg
convert: unable to open image 'D:\Project\pdf-jpg convertor\tmp/test.pdf': No such file
or directory # error/blob.c/OpenBlob/3570.
convert: no images defined `awbtest.jpg' # error/convert.c/ConvertImageCommand/3342.
at ChildProcess.exithandler (node:child_process:397:12)
at ChildProcess.emit (node:events:390:28)
at maybeClose (node:internal/child_process:1064:16)
at Process.ChildProcess._handle.onexit (node:internal/child_process:301:5) {
killed: false,
code: 1,
signal: null,
cmd: 'magick convert D:\Project\pdf-jpg convertor\tmp/test.pdf -quality 100
awbtest.jpg'
}

Related

I can't run commands from nodejs as child_process, or read the file system in an electron application with snap package configuration

I have working on an electron desktop application, the app is quite simple its about building a file browser for Linux. From Nodejs apis I use child_process, fs, path, os, and so on.
I am using electron-builder to package and build the application.
When I build for linux with target like "zip", "deb", "rpm", the application works as expected.
But when I compile for snap. I can't run commands like:
const util = require('util');
const exec = util.promisify(require('child_process').exec);
await exec('which code');
.....
await openExternalApp('code -n', `"${file.path}"`)
.....
async function openExternalApp(cmd, path) {
const util = require('util');
const exec = util.promisify(require('child_process').exec);
await exec(`${cmd} ${path}`);
}
.....
I got an error:
Error: Command failed: which code
at ChildProcess.exithandler (node:child_process:406:12)
at ChildProcess.emit (node:events:390:28)
at maybeClose (node:internal/child_process:1064:16)
at Socket.<anonymous> (node:internal/child_process:450:11)
at Socket.emit (node:events:390:28)
at Pipe.<anonymous> (node:net:687:12) {
killed: false,
code: 1,
signal: null,
cmd: 'which code',
stdout: '',
stderr: ''
}
Error: Command failed: which code
Also in my program when i have to read directories of the file system related with hard drive or another location simply i can't.
I've started to study a little bit the docs in snap store and I realized that you have to configure the slot, layout and slugs to access the whole file system, and perhaps to run bash or shell command like the one above.
After several configuration i continue with the same issues. Here is my configuration for snap in pakage.json
"snap": {
"plugs": [
"desktop",
"desktop-legacy",
"home",
"x11",
"unity7",
"browser-support",
"network",
"gsettings",
"opengl",
"block-devices",
"classic-support",
"hardware-observe",
"home",
"system-backup",
"system-observe",
"process-control",
"hostname-control",
"removable-media",
{
"system-files": {
"read": [
"/etc",
"/usr",
"/home",
"/media",
"/mnt",
"/var",
"/temp",
"/opt",
"/sys",
"/dev",
"/bin",
"/snap"
],
"write": [
"/home",
"/mnt"
]
}
}
],
"desktop": {
"Encoding": "UTF-8",
"Icon": "${SNAP}/icon.png"
}
}
snap image config in pakage.json

Node.js child_process has no access to global modules

I have installed a npm packages globally in my Kubuntu 19.04
$ npm install -g cordova
/home/username/.npm-global/bin/cordova -> /home/username/.npm-global/lib/node_modules/cordova/bin/cordova
+ cordova#9.0.0
updated 1 package in 7.299s
I can access it from shell
$ cordova -v
9.0.0 (cordova-lib#9.0.1)
But I can't access it from a simple node script with spawn:
const { spawn } = require( 'child_process' );
const cmd = spawn( 'cordova', [ '-v' ] );
cmd.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
} );
Running it results in the following:
$ node test1.js
events.js:298
throw er; // Unhandled 'error' event
^
Error: spawn cordova ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
at onErrorNT (internal/child_process.js:467:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Emitted 'error' event on ChildProcess instance at:
at Process.ChildProcess._handle.onexit (internal/child_process.js:273:12)
at onErrorNT (internal/child_process.js:467:16)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
errno: -2,
code: 'ENOENT',
syscall: 'spawn cordova',
path: 'cordova',
spawnargs: [ '-v' ]
}
But when using absolute path:
const { spawn } = require( 'child_process' );
const cmd = spawn( '/home/username/.npm-global/bin/cordova', [ '-v' ] );
cmd.stdout.on( 'data', data => {
console.log( `stdout: ${data}` );
} );
I get the expected result:
$ node test1.js
stdout: 9.0.0 (cordova-lib#9.0.1)
My script above is just a testcase, since I have problem to add/run cordova specific stuff in vue-cli-plugin-cordova and quasar. I tracked it down, that the global path is the problem.
Update
I think I found the problem, but not sure how to solve it. When setting /bin/bash as shell, it works:
cmd = spawn('cordova', ['-v'], {
shell: '/bin/bash'
});
Not sure, why this is needed and why the packages vue-cli-plugin-cordova and quasar don't do it.
Ok, after hours of research and tryouts, I have uninstalled node, installed nvm and latest node, set
nvm use --delete-prefix v13.7.0 --silent >> /dev/null
and added this to ~/.bashrc
and now everything works
how I solve my error, I changed the environment variable PATH: to C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;{plus program paths}
which is
C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Program Files\nodejs
in my PATH

Unable to convert pdf to image on AWS Lambda

I have a Nodejs 8.10 lambda which converts pdf to png which was working fine untill few days ago.
This is the error which seems to be caused because of AWS update
https://aws.amazon.com/blogs/compute/upcoming-updates-to-the-aws-lambda-execution-environment/
{
Error: Command failed: convert -density 200 -quality 75 "/tmp/temp_file.pdf[0]" "/tmp/temp_file-0.png"
convert: unable to load module `/usr/lib64/ImageMagick-6.7.8/modules-Q16/coders/pdf.la': file not found # error/module.c/OpenModule/1278.
convert: no decode delegate for this image format `/tmp/temp_file.pdf' # error/constitute.c/ReadImage/544.
convert: no images defined `/tmp/temp_file-0.png' # error/convert.c/ConvertImageCommand/3046.
}
The error was resolved by adding this public layer which will stop working after July 22:
arn:aws:lambda:::awslayer:AmazonLinux1703
I tried creating ImageMagick Static Binaries for AWS Lambda.
I followed these instructions for ImageMagic version 6.9.10-5
https://gist.github.com/bensie/56f51bc33d4a55e2fc9a
https://imagemagick.org/download/ImageMagick-6.9.10-55.tar.gz
Folder structure for lambda:
I tried basic resize of png image:
var IM_PATH = "var/task/imagemagick/bin/";
process.env['LD_LIBRARY_PATH'] = 'var/task/imagemagick/lib/';
process.env['PATH'] = process.env['PATH'] + ':' + IM_PATH + ':' + process.env['LD_LIBRARY_PATH'];
var gm = require('gm').subClass({
imageMagick: true,
appPath: 'var/task/imagemagick/bin/',
});
gm('image.png')
.resize(240, 240, '!')
.write('/tmp/resize.png', function (err) {
if (!err) console.log('done');
else {
console.log(err);
}
});
Tried running on Node 8.10 and node 10.x lambdas and here the the errors:
1) Node 8.10
{ Error: Command failed: convert: UnableToOpenConfigureFile `delegates.xml' # warning/configure.c/GetConfigureOptions/677.
convert: NoDecodeDelegateForThisImageFormat `PNG' # error/constitute.c/ReadImage/560.
convert: NoImagesDefined `/tmp/resize.png' # error/convert.c/ConvertImageCommand/3235.
at ChildProcess.onExit (/var/task/node_modules/gm/lib/command.js:301:17)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at maybeClose (internal/child_process.js:925:16)
at Socket.stream.socket.on (internal/child_process.js:346:11)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at Pipe._handle.close [as _onclose] (net.js:567:12) code: 1, signal: null }
2) Node 10.x
{ Error: Command failed: var/task/imagemagick/bin/convert: error while loading shared libraries: libgomp.so.1: cannot open shared object file: No such file or directory
at ChildProcess.onExit (/var/task/node_modules/gm/lib/command.js:301:17)
at ChildProcess.emit (events.js:189:13)
at ChildProcess.EventEmitter.emit (domain.js:441:20)
at maybeClose (internal/child_process.js:970:16)
at Socket.stream.socket.on (internal/child_process.js:389:11)
at Socket.emit (events.js:189:13)
at Socket.EventEmitter.emit (domain.js:441:20)
at Pipe._handle.close (net.js:597:12) code: 127, signal: null }

Aws lambda binary file EACCES error

I got Error: spawn EACCES error at the following line when I tried to execute this in aws lambda.
var zip = childProcess.spawn('zip', [
'-r',
job.destination.name,
'./'
], {
cwd: temporaryDirectoryPath
});
I have a binary file 'zip'.
Full error trace:
Error: spawn EACCES
at exports._errnoException (util.js:1018:11)
at ChildProcess.spawn (internal/child_process.js:319:11)
at Object.exports.spawn (child_process.js:378:9)
at createCompressedFile (/var/task/index.js:141:32)
at /var/task/node_modules/async/lib/async.js:718:13
at iterate (/var/task/node_modules/async/lib/async.js:262:13)
at /var/task/node_modules/async/lib/async.js:274:29
at /var/task/node_modules/async/lib/async.js:44:16
at /var/task/node_modules/async/lib/async.js:723:17
at /var/task/node_modules/async/lib/async.js:167:37
Finally, it worked for me. So all errors like EACCES, ENOEN... has gone.
child_process.spawnSync('mybinary', [], {
shell: true
})

ImageMagick 7.0.4 / NodeJS 6.9.2 / GPLGS 9.15 / Win 7: Failing to convert files

Problem
I am able to do a conversion from PDF to another image format from the command-line using the convert.exe ImageMagick command. However, when running the following JS in Node I get the error that follows the code below.
JavaScript
fs = require('fs');
var PDFImage = require("pdf-image").PDFImage;
console.log("Start");
var pdfImage = new PDFImage('test.pdf');
pdfImage.convertPage(0).then(function (imagePath) {
// 0-th page (first page) of the slide.pdf is available as slide-0.png
console.log('Converted');
fs.existsSync('test-0.png') // => true
}, function (err) {
console.log(err);
});
package.json
{
"name": "pdftester",
"version": "1.0.0",
"description": "PDF Tester",
"main": "PDFTester.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "John Doe",
"license": "ISC",
"dependencies": {
"async": "^2.1.4",
"imagemagick": "^0.1.3",
"pdf-image": "^1.1.0",
"pdftotextjs": "^0.4.0"
}
}
Results
Start
{ message: 'Failed to convert page to image',
error:
{ Error: Command failed: convert 'test.pdf[0]' 'test-0.png'
convert: unable to open image ''test.pdf[0]'': No such file or directory # error/blob.c/OpenBlob/2691.
convert: unable to open module file 'C:\ImageMagick-7.0.4-Q16\modules\coders\IM_MOD_RL_PDF[0]'_.dll': No such file or directory # warning/module.c/GetMagickModulePath/680.
convert: no decode delegate for this image format `PDF[0]'' # error/constitute.c/ReadImage/509.
convert: no images defined `'test-0.png'' # error/convert.c/ConvertImageCommand/3254.
at ChildProcess.exithandler (child_process.js:206:12)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:498:12)
killed: false,
code: 1,
signal: null,
cmd: 'convert \'test.pdf[0]\' \'test-0.png\'' },
stdout: '',
stderr: 'convert: unable to open image \'\'test.pdf[0]\'\': No such file or directory # error/blob.c/OpenBlob/2691.\r\nconvert: unable to open module file \'C:\\ImageMagick-7.0.4-Q16\\modules\\coders\\IM_MOD_RL_PDF[0]\'_.dll\': No such file or directory # warning/module.c/GetMagickModulePath/680.\r\nconvert: no decode delegate for this image format `PDF[0]\'\' # error/constitute.c/ReadImage/509.\r\nconvert: no images defined `\'test-0.png\'\' # error/convert.c/ConvertImageCommand/3254.\r\n' }
Analysis
The offending line is the command-line built for convert.exe, that is:
'convert \'test.pdf[0]\' \'test-0.png\''
What is adding the extra slashes, ticks ('), and '[0]'?
Thanks in advance!
according to your question , extra slashes denotes to enter in folder.
you have to put your file with respect to server file from where it starts. or put your pdf file into from where your running your apps.

Resources