Node.js file server on Rpi3 Jesse - javascript

I have a file server that works perfectly on my Rpi 2 with Raspian and I have been trying to migrate it to a newer Rpi3 with Jesse. Every time I try to run it I get the following error stack
/media/pi/DemoServer.js:82
server.listen(port, () => {
^
SyntaxError: Unexpected token )
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3
Any suggestions on why this is occurring? Is there a subtle nuance between the two distributions that I should address?
Here is the code for the server (with some omissions).
const express = require('express');
const formidable = require('formidable');
const fs = require('fs-extra');
const http = require('http');
const util = require('util');
const serveIndex = require('serve-index');
const serveStatic = require('serve-static');
const path = require('path');
const server = express();
const port = process.env.PORT || 1001;
const dirToServe = '/media/pi/Shared';
function setHeaders(res, filepath) {
res.setHeader('Content-Disposition', 'attachment; filename=' + path.basename(filepath));
}
server.post('/media/pi/Shared', function(req,res) {
});
//Serve the static folder and the index of the folder
server.use('/', serveIndex(dirToServe, { icond: true }));
server.use('/', serveStatic(dirToServe, {setHeaders: setHeaders }));
server.listen(port, () => {
console.log('listening on port ' + port);
});

Related

node.js throws error when I try to require local module

Where am I going wrong while requiring a local module?
Below are my code snippets for requiring a local module.
I have placed the game.js file in the following path /public/javascript/game.js whereas the app.js is being placed in the following path /app.js
//game.js
let players = [];
let selectedPlayers = [];
let remainingPlayers = 11;
for(var i=0; i<2; i++){
players.push($(".card > button").eq(i).attr("value"));
}
exports.players = players;
//app.js
const express = require("express");
const bodyParser = require("body-parser");
const mySql = require("mySql");
const game = require("./game");
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
app.get("/play", function(req, res){
res.render("PlayGame");
console.log(game.players);
});
app.listen(process.env.PORT || 3000, function(req, res){
console.log("Listening on port 3000");
});
When I run this, I get the following error in my terminal
internal/modules/cjs/loader.js:883
throw err;
^
Error: Cannot find module './game'
Require stack:
- C:\Users\akash\Desktop\FantasyCricket\app.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
at Function.Module._load (internal/modules/cjs/loader.js:725:27)
at Module.require (internal/modules/cjs/loader.js:952:19)
at require (internal/modules/cjs/helpers.js:88:18)
at Object.<anonymous> (C:\Users\akash\Desktop\FantasyCricket\app.js:4:14)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12) {
code: 'MODULE_NOT_FOUND',
requireStack: [ 'C:\\Users\\akash\\Desktop\\FantasyCricket\\app.js' ]
}
They are not on the same folder, so your require must be:"
const game = require("./public/javascript/game");

Node js error: [nodemon] app crashed - waiting for file changes before starting

After importing the expressEdge I got stucked.
const path =require('path');
const expressEdge = require('express-edge');
const express = require('express');
const app = new express();
app.use(express.static('public'));
app.use(expressEdge);
app.set("views", `${__dirname}/views`);
app.get('/', (req, res) => {
res.render('index')
})
app.get('/about.html', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/about.html'));
})
app.get('/contact.html', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/contact.html'));
})
app.get('/post', (req, res) => {
res.sendFile(path.resolve(__dirname, 'pages/post.html'));
})
app.listen(5000, () => {
console.log('App listening o port 5000');
})
while trying to introduce the expressEdge I got these error below:
at Object.<anonymous> (C:\Users\Globalwise\Desktop\nodejs-blog\index.js:11:5)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
[nodemon] app crashed - waiting for file changes before starting...
Your help would be appreciated.
Thanks all in advance.
When you require('express-edge), it brings in an object. When you register the middleware you need to pass the engine. You have two options...
Access the engine property from the required object
const expressEdge = require('express-edge');
app.use(expressEdge.engine);
Or access the engine property on the require
const expressEdgeEngine = require('express-edge').engine;
app.use(expressEdgeEngine);
https://www.npmjs.com/package/express-edge

Type error: cannot find module body-parser

I tried making a project on my own and this error happened. I couldn't fix it. It just somehow happens and I am so confused where to start looking for the error.
app.js
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.set('view engine', 'ejs');
app.set('views', 'views');
const adminData = require('./routes/admin');
const shopRoutes = require('./routes/shop');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminData.routes);
app.use(shopRoutes);
app.use((req, res, next) => {
res.status(404).render('404', { pageTitle: 'Page Not Found' });
});
app.listen(3000);
admin.js
const path = require('path');
const express = require('express');
const rootDir = require('../util/path');
const router = express.Router();
const products = [];
// /admin/add-product => GET
router.get('/add-product', (req, res, next) => {
res.render('add-product', {
pageTitle: 'Add Product',
path: '/admin/add-product',
formsCSS: true,
productCSS: true,
activeAddProduct: true
});
});
// /admin/add-product => POST
router.post('/add-product', (req, res, next) => {
products.push({ title: req.body.title });
res.redirect('/');
});
exports.routes = router;
exports.products = products;
shop.js
code snippet of shop.js
This is my error.
I am making a webpage for the first time using this.
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module 'body-parser'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object.<anonymous> (C:\Users\User\Documents\My Website\05-working-on-layout-with-partials\app.js:4:20)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
[nodemon] app crashed - waiting for file changes before starting...
Please try to install the required body-parser module,
Use following command to do so.
npm install body-parser
Please install the dependency i.e body-parser
npm i body-parser --save
Error is on the 4th line of app.js its not getting the body-parser module

Express JS REST API with MySQL

I am doing an exercise with Express.js and MySQL. At the moment I have 4 files. The error is,
TypeError: areas.getAreas is not a function
at Object.<anonymous> (/--/--/--/src/routes/userRoutes.js:4:13)
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)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/--/--/--/src/app.js:10:20)
at Module._compile (module.js:653:30)
But I am sure I am declaring the variable and function so, I don't understand why is it happening.
I tried to get the value of the variable areas in the userRoutes.js file but console just show me an "{}". I also tried to change the sintaxis of the function of the areas.js file, writing it as function and not like an object.
The main file is, app.js and it contains:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const connection = require('/--/--/--/db/connection.js');
const userRoutes = require('/--/--/--/routes/userRoutes.js');
app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
connection(mysql);
userRoutes(app);
app.listen(app.get('port'), ()=> {
console.log('server on port 3000');
});
The next files are:
connection.js
'use strict';
module.exports = function connection(mysql){
mysql.createConnection({
host: 'http://x.x.x.x',
user: 'xxxxxxx',
password: 'xxxxxxx',
database: 'xxxxxxx'
})
};
areas.js
'use strict';
let areasModel = {};
areasModel.getAreas = (callback) => {
if(connection) {
connection.query(
"SELECT * FROM areas",
(err, rows) => {
if(err) {
throw err;
}
else {
callback(null, rows);
}
}
);
}
};
module.exports = areasModel;
userRoutes.js
'use strict';
const areas = require('../models/areas');
module.exports = function (app) {
app.get("/", (req,res)=>{
areas.getAreas((err, data) => {
res.json([]);
});
});
}
try importing connection.js in areas.js,
maybe because never enter in that if statement, returns undefined

Socket io implementation, Getting TypeError('"listener" argument must be a function')

I am trying to implement Socket IO with my angular Js project. I am new into this, please help.
This is my server.js file
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "app")));
io.on('connection'), function(socket){
console.log('new connection made');
}
server.listen(port, function(){
console.log('Listening to port '+ port);
})
I have copied the socket.io.js file from socket.io-client and put it in my lib folder. So my index.html has
<script src="lib/js/socket.io.js"></script>
//all other includes required
<body>
//code here
</body>
heres is the error I get to see when I execute nodemon server.js
[nodemon] starting `node server.js`
events.js:216
throw new TypeError('"listener" argument must be a function');
^
TypeError: "listener" argument must be a function
at _addListener (events.js:216:11)
at Namespace.addListener (events.js:275:10)
at Server.(anonymous function) [as on]
(D:\SocketIOExperiment\ProjExperiment\node_modules\socket.io\lib\index
.js:456:29)
at Object.<anonymous>
(D:\SocketIOProject\SmartAdminExperiment\server.js:11:4)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
[nodemon] app crashed - waiting for file changes before starting...
Small typo on your code.Try this :
var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "app")));
io.on(('connection'), function(socket){
console.log('new connection made');
})
server.listen(port, function(){
console.log('Listening to port '+ port);
})
Remember, io.on(event,cb) is a function call that registers the cb function to the event.

Categories

Resources