I copied a code from StackOverflow to read text from a base64 of an image:
let base64 = req.body.toString("base64");
let imageBuffer = Buffer.from(base64, "base64");
const worker = createWorker();
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
console.log("Recognizing...");
const { data: { text } } = await worker.recognize(imageBuffer);
console.log("Recognized text:", text);
await worker.terminate();
})();
But I a getting this Error:
Error opening data file ./eng.traineddata
Please make sure the TESSDATA_PREFIX environment variable is set to your "tessdata" directory.
Failed loading language 'eng'
Tesseract couldn't load any languages!
Recognizing...
AdaptedTemplates != nullptr:Error:Assert failed:in file /workspace/tesseract/src/classify/adaptmatch.cpp, line 196
undefined
undefined
C:\Users\jaysm\OneDrive\Desktop\QBase\node_modules\tesseract.js\src\createWorker.js:173
throw Error(data);
^
Error: RuntimeError: abort(undefined). Build with -s ASSERTIONS=1 for more info.
at ChildProcess.<anonymous> (C:\Users\jaysm\OneDrive\Desktop\QBase\node_modules\tesseract.js\src\createWorker.js:173:15)
at ChildProcess.emit (events.js:315:20)
at emit (internal/child_process.js:903:12)
at processTicksAndRejections (internal/process/task_queues.js:81:21)
[nodemon] app crashed - waiting for file changes before starting...
What is the problem with my code?
I found some solutions of this error but they were with python or some other languages but none with NodeJS.
Actually my problem was not of setting TESSDATA_PREFIX as environment variable but i had not placed the eng.traineddata file in the base directory.
I placed the eng.traineddata file and the issue was resolved!
Related
I'm trying to simply test for an existence of a file on our Google Cloud Platform (GCP) storage. I'm using GCP buckets on express js servers. Below is essentially a very simple exampled copied off of https://googleapis.dev/nodejs/storage/latest/File.html#exists
EDIT: This is how I authenticate the GCP key:
const { Storage } = require('#google-cloud/storage');
const storage = new Storage({
projectId: 'my-cloud',
keyFilename: process.env.GOOGLE_APPLICATION_CREDENTIALS,
});
const bucketName = 'my-ci';
(With small changes, I realise you are supposed to return data[0])
const bucket = storage.bucket(bucketName);
const file = bucket.file(path);
const exists = await file.exists().then(data => {
return data
})
But when I try run this, I get the error:
[nodemon] starting `node --inspect server/server.js`
Debugger listening on ws://127.0.0.1:9229/9a677766-4a93-4499-b57c-55f5f05096d7
For help, see: https://nodejs.org/en/docs/inspector
Server listening on port 4000!
/opt/node_modules/jwa/index.js:115
return new TypeError(errMsg);
^
TypeError: key must be a string, a buffer or an object
at typeError (/opt/node_modules/jwa/index.js:115:10)
at checkIsPrivateKey (/opt/node_modules/jwa/index.js:61:9)
at Object.sign (/opt/node_modules/jwa/index.js:147:5)
at Object.jwsSign [as sign] (/opt/node_modules/jws/lib/sign-stream.js:32:24)
at JWTAccess.getRequestHeaders (/opt/node_modules/google-auth-library/build/src/auth/jwtaccess.js:87:31)
at JWT.getRequestMetadataAsync (/opt/node_modules/google-auth-library/build/src/auth/jwtclient.js:76:51)
at JWT.getRequestHeaders (/opt/node_modules/google-auth-library/build/src/auth/oauth2client.js:238:37)
at GoogleAuth.authorizeRequest (/opt/node_modules/google-auth-library/build/src/auth/googleauth.js:593:38)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Since the error message did not give a useful traceback, I did some digging on my own. Through putting console.log statements everywhere, I narrowed it down to the line
const exists = await file.exists().then(data => {
return data
})
and tried various approaches from removing the .then(...) clause, to removing the await (which, does work until the promise is resolved). None of these seemed to have worked.
What may be potential causes of this?
Eventually figured it out - it was due to the GCP key being an older version of the key. If you get an error like above, try to check that your key is correct.
I am very new to both python and node.js. Basically I am trying to call a python script from node.js.Any help would be much appreciated.
I have installed python-shell npm package.
When I run the python script from cmd, it works fine and I can see the output.
I have installed python 3.8.
This is my python script:
# script.py
my_name = 'Lily'
my_age = 22
my_height = 172 # cm
my_weight = 71 # kg
my_eyes = 'Brown'
my_teeth = 'White'
my_hair = 'Black'
print ("Let's talk about %s." % my_name)
print ("He's %d centimeters tall." % my_height)
print ("He's %d kilograms heavy." % my_weight)
print ("Actually that's not too heavy.")
print ("He's got %s eyes and %s hair." % (my_eyes, my_hair))
print ("His teeth are usually %s depending on the coffee." % my_teeth)
# this line is tricky, try to get it exactly right
print ("If I add %d, %d, and %d I get %d. I don't know what that means but, whatever." % (
my_age, my_height, my_weight, my_age + my_height + my_weight))
Here is my node.js script:
function Runpy(){
var {PythonShell} = require('python-shell');
var options = {
mode: 'text',
pythonPath: 'C:/Users/User1/AppData/Local/Programs/Python/Python38',
pythonOptions: ['-u'],
scriptPath: 'C:/PythonScripts/script.py'
};
PythonShell.run('script.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
}
return Runpy();
When I run node ./sample.js I get the following error:
events.js:174
throw er; // Unhandled 'error' event
^
Error: spawn C:/Users/User1/AppData/Local/Programs/Python/Python38 ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
at onErrorNT (internal/child_process.js:415:16)
at process._tickCallback (internal/process/next_tick.js:63:19)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Emitted 'error' event at:
at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
at onErrorNT (internal/child_process.js:415:16)
[... lines matching original stack trace ...]
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
I have referred to this stackoverflow post Using PythonShell module in Nodejs where it is suggested to use absolute path to the script and also correct path to the python executable which i am doing but still getting the above error.
Thanks!
I got this working. The path to the python executable was incomplete. I was just pointing to 'C:/Users/user1/AppData/Local/Programs/Python/Python38' which should be 'C:/Users/user1/AppData/Local/Programs/Python/Python38/python3'. Indeed a silly mistake
Trying to run the command mentioned in sections below, it is intended to run retire.js on some javascript files/libraries and pipe the output in a json file. The command works and produces output in a json file but ends with an error.
When I try the same command directly by copy pasting the command in command line it works without an error.
I have tried the exexSync version and shelljs as well though get error in Shelljs as well. However, I am not able to understand what is causing the problem.
using node-exec-promise.exec :
exec('node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json').
then(function(retire_out){
console.log('Retire Command Success ');
console.log(' Retire_out Result ',retire_out);
return retire_out;
}, function(err){
console.error(err)
}
Using Shelljs:
if (shell.exec('node
C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Expected Result is a Json file with known vulnerabilities found by retire.js, the file gets populated and it has valid json.
However, I get the following error in command line:
{ Error: Command failed: node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json
at ChildProcess.exithandler (child_process.js:294:12)
at ChildProcess.emit (events.js:189:13)
at maybeClose (internal/child_process.js:970:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
killed: false,
code: 13,
signal: null,
cmd:
'node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json' }
Because retire exits with an exitcode of 13 if there are vulnerabilities found, you'll want a .catch before any .then to "allow" exitcode 13.
Also, since you've specified --outputpath for retire, the output will NOT go to stdout, so you will need to read the outputfile in the .then code - also, since retire would return an "error" (13) - node-exec-promise doesn't even give you access to stdout/stderr in the err that is passed to the .catch code anyway!
The following is pseudo-code, since I'm not fully familiar with node-exec-promise:
exec('node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json')
.catch(err => {
if (err.code !== 13) {
throw err;
}
})
.then(() => {
// read the output file if you want to display it here
})
.catch(err => {
//handle other errors here
});
I'm using a library called python-shell to try and send data back and forth between node and python.
The code below should work but when I run it I get this error:
events.js:160
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at exports._errnoException (util.js:1022:11)
at Socket._writeGeneric (net.js:712:26)
at Socket._write (net.js:731:8)
at doWrite (_stream_writable.js:334:12)
at writeOrBuffer (_stream_writable.js:320:5)
at Socket.Writable.write (_stream_writable.js:247:11)
at Socket.write (net.js:658:40)
at PythonShell.send (C:\Users\user\Desktop\node py project\fourth draft\node
_modules\python-shell\index.js:205:16)
at Object.<anonymous> (C:\Users\user\Desktop\node py project\fourth draft\in
dex.js:4:9)
at Module._compile (module.js:570:32)
my index.js:
var PythonShell = require('python-shell');
var pyshell = new PythonShell('script.py');
pyshell.send(JSON.stringify([1,2,3,4,5]));//the problem function
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err){
throw err;
};
console.log('finished');
});
my script.py:
import sys, json
#Read data from stdin
def read_in():
lines = sys.stdin.readlines()
# Since our input would only be having one line, parse our JSON data from that
return json.loads(lines[0])
def main():
#get our data as an array from read_in()
lines = read_in()
# Sum of all the items in the providen array
total_sum_inArray = 0
for item in lines:
total_sum_inArray += item
#return the sum to the output stream
print total_sum_inArray
# Start process
if __name__ == '__main__':
main()
I think it has to do with the env path for python on win 7.
Any ideas? Library docs are located here: https://github.com/extrabacon/python-shell. Also I'm on Windows 7 Node v6.9.2 Python v3.6.1.
Try passing the parameter of python path to the script as below
var pyshell = new PythonShell('script.py',{pythonPath : '<path/to/python>'});
In this way you are explicitly setting the path to python executable command, regardless of any OS.
Here is reference of all the available options, that can be passed to the python-shell constructor.
Hope this fixes the issue, if it has to do anything with the Python path issues.
I'm using the html-pdf module to generate pdfs, using the following code:
var ejs = require('ejs');
var fs = require('fs');
var pdf = require('html-pdf');
var build = function (template, data) {
var html = ejs.compile(fs.readFileSync(template, 'utf8'));
html = html(data);
return html;
}
pdf.create(build('views/print_templates/pm_export_pdf.ejs',
{rows:resolve(rows, user_rows, table_rows,
subproject_rows, milestone_rows, release_rows)}), pdfconfig)
.toFile(function (err, pdf) {
if (err)
return console.log(err);
res.sendFile(pdf.filename);
});
PDFconfig is the config variable for html-pdf. And resolve is my own db resolve function, which is not very relevant in this story.
When I run this locally on OSX 10.10 on my MacBook Pro this works like a charm. But when I run this on my server(centOS), I get the following error:
events.js:72
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at errnoException (net.js:904:11)
at Object.afterWrite (net.js:720:19)
Has this something to do with permissions maybe? I'm not really sure what I'm doing wrong..
I run the following versions:
Node: 0.10.31
Express: 4.10.7
html-pdf: 1.2.0
For future purposes:
I figured that I had to rebuild my node-modules. I think I accidentally copied the node-modules folder over to the test server on centOS, and phantomjs had build it's dependencies for OSX. I'm still not sure how the error that it threw correspondents with that, but it fixed it.
Also be sure that you have FreeType and fontconfiglib installed.