how to use Tesseract.recognize in nodejs - javascript

I want to make an OCR program but I fund some problems during the declaration of 'Tesseract.recognize' method
here is my code :
const express = require('express');
const fs= require('fs');
const multer = require('multer');
const Tesseract = require('Tesseract.js');
const app = express();
// app.use(bodyParser.urlencoded({extended: true}))
const PORT = process.env.PORT | 5000;
var Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, 'images')
},
filename: function (req, file, callback) {
callback(null, file.orignalname);
}
});
var upload = multer({
storage: Storage
}).array('image', 3);
//route
app.post('/', (req, res) => {});
app.post('/upload', (req, res) => {
console.log(req.file);
upload(req, res , err => {
if (err) {
console.log(err);
return res.send('somthing went wrong');
}
return res.send('file uploaded successfully');
});
});
var image = fs.readFileSync(__dirname + '/images/cv.jpg',
{
encoding:null
});
Tesseract.recognize(image)
.progress(function(p) {
console.log('progress', p);
})
.then(function(result) {
res.send('result', result);
});
app.listen(PORT, () => {
console.log('Server running on PORT ${PORT}')
});
and this is my terminal result:
.progress(function(p) {
^
TypeError: Tesseract.recognize(...).progress is not a function
at Object.<anonymous> (C:\Users\de\Desktop\MR.Azmani Project\ANGULAR\ocr\server.js:46:6)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
[nodemon] app crashed - waiting for file changes before starting...
and this it what is the result how should look like in the treminal during the process
and this is the final result in the termilal
thank you

.progress was removed in version 2 of tesseract.js (there's a blog post about that here. Version one is still on Github here, and probably still works, so you can npm i tesseract.js#1.0.19 to get the behavior you're expecting, or see the docs and examples for the current version to get your code updated for v2.

Related

Router.use() requires a middleware function but got a string

I get this error
E:\server\node_modules\express\lib\router\index.js:469
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a string
at Function.use (E:\PROJECT\New folder\New folder\server\node_modules\express\lib\router\index.js:469:13)
at Function. (E:\PROJECT\New folder\New folder\server\node_modules\express\lib\application.js:227:21)
at Array.forEach ()
at Function.use (E:\PROJECT\New folder\New folder\server\node_modules\express\lib\application.js:224:7)
at Object. (E:\PROJECT\New folder\New folder\server\index.js:27:5)
at Module._compile (node:internal/modules/cjs/loader:1126:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
at Module.load (node:internal/modules/cjs/loader:1004:32)
at Function.Module._load (node:internal/modules/cjs/loader:839:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
Index.js
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const todoRoute = "./Routes/todo-route.js";
const app = express();
dotenv.config();
app.use(cors());
app.use(express.json());
mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
})
.then(console.log("DB Connected successfuly"))
.catch((error) => {
console.log(error);
});
app.get("/", (req, res) => {
res.send("this is the homepage");
});
app.use("/api/todos", todoRoute);
const PORT = 5000 || process.env.PORT;
app.listen(PORT, () => {
console.log(`Listening on http://localhost:${PORT}`);
});
todo-route.js
const express = require(express);
const router = express.Router();
router.get("/", (req, res) => {
res.send("this is get route");
});
router.post("/", (req, res) => {
res.send("this is post route");
});
router.put("/:id", (req, res) => {
res.send("this is update route");
});
router.delete("/:id", (req, res) => {
res.send("this is delete route");
});
module.exports = router;
Maybe it is because you are not importing express correctly in todo-route.js
it should be:
```
const express = require("express");
```
According to official API Reference
second argument of app.use should be a callback function
so in your index.js have a line
app.use("/api/todos", todoRoute);
todoRoute should use require make that become a function

TypeError('app.use() requires a middleware function')

enter image description here
here's the app.js(--please find attached image):
//here's the app.js
const express = require("express");
const app = express();
app.use(express.json());
const morgan = require("morgan");
const mongoose = require("mongoose");
const cors = require("cors");
require("dotenv/config");
const authJwt = require("./helpers/jwt");
const errorHandler = require("./helpers/error-handler");
app.use(cors());
app.options('*', cors());
//middleware
app.use(morgan("tiny"));
app.use(authJwt());
app.use(errorHandler()); //-> **this isn't correct?**
//Importing routing of products
const categoriesRoutes = require("./routes/categories");
const productsRoutes = require("./routes/products");
const usersRoutes = require("./routes/users");
const ordersRoutes = require("./routes/orders");
const req = require("express/lib/request");
const res = require("express/lib/response");
const api = process.env.API_URL;
//routers
app.use(`${api}/products`, productsRoutes);
app.use(`${api}/categories`, categoriesRoutes);
app.use(`${api}/orders`, ordersRoutes);
app.use(`${api}/users`, usersRoutes);
//Database
mongoose
.connect(process.env.CONNECTION_STRING, {
useNewurlParser: true,
useUnifiedTopology: true,
dbName: "eshop-database",
})
.then(() => {
console.log("database connection is ready");
})
.catch((err) => {
console.log(err);
});
//Server
app.listen(3000, () => {
console.log("Server is Running http://http://localhost:3000");
});
//error image
//here's the error handler code
function errorHandler(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
}
module.exports = errorHandler;
> Blockquote (--please find attached image)
here's the error
C:\Users\steve\Backend\node_modules\express\lib\application.js:210
throw new TypeError('app.use() requires a middleware function')
^
TypeError: app.use() requires a middleware function
at Function.use (C:\Users\steve\Backend\node_modules\express\lib\application.js:210:11)
at Object.<anonymous> (C:\Users\steve\Backend\app.js:17:5)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
Your error handler function is correct, but the problem is that you're calling the function instead of passing it directly to your express app.
Remove the parenthesis after the errorHandler and it should work.
app.use(errorHandler); // Don't call errorHandler, express will call it
Think of it like this.
if I just call errorHandler() in any context it won't return anything.
That means that errorHandler() evaluates to undefined.
Now in your code, when you do app.use(errorHandler()) instead of evaluating to the following:
app.use(function(err, req, res, next){
if (err) {
res.status(500).json({message: err})
}
});
Your code is actually evaluating to
app.use(undefined);
and so express is throwing an error because undefined is not a function.

Facing problems while using HBS

I am a total noob in Backend and I am learning Express and using HBS as template engine.
This happens to me every time while using hbs partials in Express.
Code
const express = require("express");
const app = express();
const hbs = require("hbs");
const path = require("path");
const port = process.env.PORT || 3000;
// public static path
const static_path = path.join(__dirname, "../public");
const templates_path = path.join(__dirname, "../templates/views");
const partials_path = path.join(__dirname, "../templates/partials");
app.set("view engine", "hbs");
app.set("views", templates_path);
hbs.registerPartial(partials_path);
app.use(express.static(static_path));
// routing
app.get("/", (req, res) => {
res.render("index");
});
app.get("/about", (req, res) => {
res.render("about");
});
app.get("/weather", (req, res) => {
res.render("weather");
});
app.get("*", (req, res) => {
res.status(404).render("404error");
});
app.listen(port, () => {
console.log("listning on port " + port);
});
Error
throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
^
Error: Attempting to register a partial called "D:\Projects\ExpressWeb\templates\partials" as undefined
at HandlebarsEnvironment.registerPartial (D:\Projects\ExpressWeb\node_modules\handlebars\dist\cjs\handlebars\base.js:80:15)
at Instance.registerPartial (D:\Projects\ExpressWeb\node_modules\hbs\lib\hbs.js:222:35)
at Object.<anonymous> (D:\Projects\ExpressWeb\src\app.js:15:5)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
at internal/main/run_main_module.js:17:47 {
description: undefined,
fileName: undefined,
lineNumber: undefined,
endLineNumber: undefined,
number: undefined
}
Adding this to increase the discripting because Stack Overflow is not letting me post this because i am uplaoding more code than discription and i dont know what to ask more.
According to the docs it is - hbs.registerPartials(partials_path);
not hbs.registerPartial(partials_path);

How to solve "Router.use() requires a middleware function but got a Object at Function.use" error

I am getting an error when calling my router from my routes directory.I have made some changes in my code around some of the other posts on this issue but I can't get anything to solve.However i am not sure what exactly is wrong with my code below.
This is my error
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\router\index.js:458
throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))
^
TypeError: Router.use() requires a middleware function but got a Object
at Function.use (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\router\index.js:458:13)
at Function.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:220:21)
at Array.forEach (<anonymous>)
at Function.use (E:\Program Files\mean apps\shoppinglist\crud-backend\node_modules\express\lib\application.js:217:7)
at Object.<anonymous> (E:\Program Files\mean apps\shoppinglist\crud-backend\app.js:42:5)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:279:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:752:3)
[nodemon] app crashed - waiting for file changes before starting...
I have this code in my app.js
//importing modules
var express = require('express');
var mongoose = require('mongoose');
var bodyparser = require('body-parser');
var cors = require('cors');
var path = require('path');
var app = express();
const route = require('./routes/route');
//conect to the mongodb
mongoose.connect('mongodb://localhost:27017/shoppinglist');
//on connection
mongoose.connection.on('connected',()=>{
console.log('Connected to database mongodb # 27017');
});
//error
mongoose.connection.on('error',(err)=>{
if(err)
{
console.log('Error in database connection:'+ err);
}
});
//port no
const port = 3000;
//adding middleware - cors
app.use(cors());
//body - parser
app.use(bodyparser.json());
//static files
app.use(express.static(path.join(__dirname, 'public')));
//routes
app.use('/api', route);
//testing server
app.get('/',(req, res)=>{
res.send('foobar');
});
app.listen(port,()=>{
console.log('Server started at port:' + port);
});
I have this code in my route.js
const express = require('express');
const router = express.Router();
const Item = require('../model/shoppingItem');
//retriving data from db
router.get('/items', (req, res, next)=>{
Item.find(function(err, items){
if(err){
res.json(err);
}
else{
res.json(items);
}
});
});
//insert data
router.post('item', (req, res, next)=>{
let newShoppingItem = new Item({
itemName: req.body.itemName,
itemQuantity: req.body.itemQuantity,
itemBought: req.body.itemBought
});
newShoppingItem.save((err, item)=>{
if(err){
res.json(err);
}
else{
res.json({msg: 'Item has been added successfully'});
}
});
});
You are using a module that you never exported.
app.use('/api', route);
but route was never exported - that's your main issue.
in your route module you can wrap everything in export default - alternatively you can use module.exports = router
This is an open source project I was working on try following the structure, if you still have issues let me know.
https://github.com/Muhand/nodejs-server

node.js ReferenceError: server is not defined

The below code is from server.js, it's causing my server to crash with Error:
ReferenceError: server is not defined at Object. (C:\xampp\htdocs\api\src\server.js:17:18) at Module._compile (module.js:571:32) at Object.Module._extensions..js (module.js:580:10) at Module.load (module.js:488:32) at tryModuleLoad (module.js:447:12) at Function.Module._load (module.js:439:3) at Module.runMain (module.js:605:10) at run (bootstrap_node.js:418:7) at startup (bootstrap_node.js:139:9) at bootstrap_node.js:533:3
var express = require('express');
var body_parser = require('body-parser');
var app = express()
// Port config
var port = 3000;
app.use(body_parser.json());
// Use prefix of api
app.use('/api', require('../routes/api.js')(express));
app.listen(port, function(){
console.log('Server Active on', port);
});
module.exports = server;
Mocha testing (__app.js)
var request = require('supertest');
describe('API', function() {
var server;
beforeEach(function () {
server = require('../src/server.js');
});
afterEach(function () {
server.close();
});
it('/ should return specified object.', function (done) {
request(server)
.get('/api/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {"hello": "world"}, done);
});
it('/status should return specified healthy:true', function (done) {
request(server)
.get('/api/status')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {"healthy": true}, done);
});
it('/user/id should return user object with id.', function (done) {
var fakeUserID = 374;
request(server)
.get('/api/user/347' + fakeUserID)
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, {user: {id: fakeUserID}}, done);
});
});
Am I missing a package? I'm watching a video with the same exact code and it doesn't crash the server.
You want to export the app. No variable called server exists
module.exports = app;
You can then import the app elsewhere in your project using require
server is not defined anywhere. As a guess, you probably want to change the last line to:
module.exports = app;
You should try this:
const server = app.listen(port, function(){
console.log('Server Active on', port);
});

Categories

Resources