So it's the first ever program I write but when I run it in the console I get this error.
module.js:540
throw err;
^
Error: Cannot find module 'C:\Users\Daniel\Desktop\app'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3
I have no idea why this is happening as I am new but I checked the code and nothing is wrong.
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-type', 'text/plain');
res.end('Hello World!');
});
server.listen(port, hostname, () => {
console.log('Server started on port '+port);
});
It seems like the script you wanted to execute isn't named "app".
Check the Path and name of your script when you execute it with the node command.
Related
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.
I have a Node JS app which serves as a backend for a React web app. The application when started serves the React app and handles all the API calls. I connect to a MySQL database for data fetch. The app runs normally on local environment but crashes when deployed on an Ubuntu server(on AWS). On server, the app starts normally but after few seconds it crashes.
This is the error it throws when started
Error connecting: Error: connect ETIMEDOUT
at PoolConnection.Connection._handleConnectTimeout (/home/ubuntu/localSystem/node_modules/mysql/lib/Connection.js:412:13)
at Object.onceWrapper (events.js:313:30)
at emitNone (events.js:106:13)
at Socket.emit (events.js:208:7)
at Socket._onTimeout (net.js:422:8)
at ontimeout (timers.js:498:11)
at tryOnTimeout (timers.js:323:5)
at Timer.listOnTimeout (timers.js:290:5)
--------------------
at Protocol._enqueue (/home/ubuntu/localSystem/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/home/ubuntu/localSystem/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at PoolConnection.connect (/home/ubuntu/localSystem/node_modules/mysql/lib/Connection.js:119:18)
at Pool.getConnection (/home/ubuntu/localSystem/node_modules/mysql/lib/Pool.js:48:16)
at Object.<anonymous> (/home/ubuntu/localSystem/model/db.js:29:12)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
DB connection file (db.js):
var connection = mysql.createPool({
connectionLimit: 100,
host : 'xxxx',
port : xxxx,
user : 'username',
password : 'password',
database : 'myDB'
});
connection.getConnection(function(err) {
if (err) {
console.log('Error connecting: ' + err.stack)
return;
}
console.log('Connected as id ' + connection.threadId)
});
module.exports = connection;
Server.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
app = express();
var appRoutes = require('./routes/appRoutes');
app.use(express.static(path.join(__dirname, './client/build')));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', appRoutes);
module.exports = app;
index.js
var app = require('./server');
//const { connection } = require('./database');
var port = 5001;
app.set('port', port);
app.listen(app.get('port'), () => {
console.log(`server on port ${app.get('port')}`);
});
AppModel.js
var sql = require('./db.js');
//Task object constructor
var Task = function(task){
this.task = task.task;
this.status = task.status;
this.created_at = new Date();
};
Task.getAllCustomerStatusRecords = function getAllCustomerStatusRecords(result) {
sql.query("Select a, b, c, call_provider_id from myTable order by id desc limit 20", function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else {
console.log('Customer status records : ', res);
result(null, res);
}
});
sql.releaseConnection()
};
I have a similar set up for another Node app but without mysql and it runs without issues.I'm not sure why it crashes in this case.
EDIT:
The API request does make a DB call. However that is only when the user explicitly selects some options and then makes a fetch call on the webpage. Initially though, there are no outwards API calls either to Db or external services.
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
I am getting an EADDRINUSE error on nodejs when trying to run this code:
const express = require('express')
const http = require('http')
const hostname = 'localhost'
const port = 3000
const app = express()
app.use((req, res, next) => {
console.log(req.headers)
res.statusCode = 200
res.setHeader('Content-Type', 'text/html')
res.end('<html><body><h1>This is response</h1></body></html>')
})
server.listen(hostname,port, () => {
console.log(`Server running at http:${hostname}//:${port}`)
})
const server = http.createServer(app)
server.listen(hostname,port, () => {
console.log(`Server running at http:{}//:${port}`)
})
I tried changing the ports but it still gave the same error.
The peculiar this is that if I remove the hostname - "localhost" and only listen to the port the code works.
Please explain what could be the issue?
Here is the stack trace :
events.js:183
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE localhost
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at Server.setupListenHandle [as _listen2] (net.js:1350:19)
at listenInCluster (net.js:1408:12)
at Server.listen (net.js:1503:5)
at Object.<anonymous> (/media/shikhar/D/Study/git-test/node-express/index.js:30:8)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
I was starting to learn NodeJS and when I implemented the first script, I get the following error:
http.listen(3000,() => console.log('Server running on port 3000'));
^
TypeError: http.listen is not a function
at Object.<anonymous> (C:\Users\I322764\Documents\Node\HelloNode.js:11:6)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:136:18)
at node.js:963:3
The corresponding script is as follows:
'use strict';
const http = require('http');
http.createServer(
(req, res) => {
res.writeHead(200, {'Content-type':'text/html'});
res.end('<h1>Hello NodeJS</h1>');
}
);
http.listen(3000,() => console.log('Server running on port 3000'));
The version of node is 4.2.4
When you write:-
http.createServer(function(req,res){
res.writeHead(200);
res.end("Hello world");
});
http.listen(3000);
http.createServer() returns an object called Server. That Server object has listen method available. And you are trying to access that listen method from the http itself. That's why it shows that error.
so you can write it like:-
var server=http.createServer(function(req,res){
res.writeHead(200);
res.end("Hello world");
});
server.listen(3000,function(){
console.log('Server running on port 3000')
});
Now it will let your server listen on the port 3000.
listen isn't a function of http, but a method of the server you create with createServer:
var server = http.createServer((req, res) => {
res.writeHead(200, {'Content-type':'text/html'});
res.end('<h1>Hello NodeJS</h1>');
});
server.listen(3000,() => console.log('Server running on port 3000'));