I'm new to Javascript. I'm trying to load the following script using Node.js (ver. 0.8.8, it has to be done in this specific version), OS - Windows 10:
//require('look').start();
var main = require('skilap-core');
if (process.argv[2]=="automated") {
process.on("message",function (msg) {
if (msg.c == "startapp") {
var app = main.createApp(msg.data);
app.startApp(__dirname+"/data",function (err) {
process.send({c:"startapp_repl",data:err})
});
}
})
} else {
var app = main.createApp();
app.startApp(__dirname+"/data",function (err) {
if (err) console.log(err);
});
module.exports = app;
}
But I get the following error:
> TypeError: Object #<Object> has no method 'createApp'
at Object.<anonymous> D:\Downloads\skilap\skilap\app.js:13:17)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback(node.js:244:9)
As I understand, the module loads correctly, but doesn't compile. I've done research in the web and also saw other related questions on this site, but I cannot see what the problem actually is. What does the error mean and what needs to be changed to launch the app? Any help would be appreciated.
You require a module I've never heard of:
var main = require('skilap-core');
This is a javascript object. In your code you are trying to call a createApp() method on that object:
var app = main.createApp();
The main object does not have the createApp() function.
I would use a debugger or insert a console.log(main) after the require to see what the object actually looks like.
I used npm pack skilap-core to download it as a tgz file and examine it. There doesn't appear to be a createApp() function at all. It appears to want to take some kind of custome webapp as a parameter:
module.exports = function (webapp) {
var app = webapp.web;
var ctx = webapp._ctx;
var prefix = webapp.prefix;
var api = webapp;
app.get(prefix, function (req, res, next) {
res.redirect(prefix+"/user");
})
app.get("/", webapp.layout(), function(req, res, next) {
...
I changed the line var main = require('skilap-core') to var main = require('./modules/core/lib/core.js') (the path to the module file) and the module started working.
Related
I have a modular based js Frontend. It only contains nodemon and express packages. I currently have src elements within my index.html, which point to my js modules. Or at least I believe that src elements are properly acquiring my files, I could be wrong. Here is a code snippet.
<script src="../index.js"></script>
<script src="../src/ingredient/ingredient.js"></script>
<script src="../src/ingredient/ingredientService.js"></script>
<script src="../src/user/user.js"></script>
<script src="../src/user/userService.js"></script>
<script src="../src/category/category.js"></script>
<script src="../src/category/categoryService.js"></script>
<script src="../src/project/project.js"></script>
<script src="../src/project/projectService.js"></script>
Within my index.js, I am attempting to initialize class objects. My current setup does not allow index.js to acquire outside modules and I cannot figure out why. Do I need another package like webpack to bundle it all together or perhaps its an issue with my code? Here is the error
const ingredientService = new IngredientService(base_url)
^
ReferenceError: IngredientService is not defined
at Object.<anonymous> (/Users/jasondavis/Flatiron/code/ProjitekFrontEnd/index.js:14:29)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975: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
INDEX.JS
const express = require('express');
const app = express();
const port = 3001;
app.use(express.static('public'));
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});
//USING NODEMON.JS
const base_url = "http://localhost:3000/api/v1"
//NEED TO ACQUIRE CLASS MODULE INSIDE SRC DIR
const ingredientService = new IngredientService(base_url)
const categoryService = new CategoryService(base_url)
const projectService = new ProjectService(base_url)
const deleteBttn = document.querySelector("deleteProject")
Ingredient.ingredientForm.addEventListener('submit', submitIngredient)
Project.projectForm.addEventListener('submit', submitProject)
Project.editProjectForm.addEventListener('submit', updateProject)
Project.testForm.addEventListener('submit', submitTest)
categoryService.getCategories()
ingredientService.getIngredients()
projectService.getProjects()
function showProject(){
event.preventDefault()
projectService.showProject()
}
function submitIngredient(){
ingredientService.createIngredient()
}
function submitProject(event){
projectService.createProject()
}
function updateProject(event){
projectService.backEndedit()
}
function submitTest(event){
event.preventDefault()
Project.submitTest()
}
function updateIngredient(event){
ingredientService.backEndedit()
}
document.addEventListener('DOMContentLoaded', () => {
Project.scrollAble()
})
What I am able to do so far: Render index.html and index.js contents to DOM
GITHUB REPO: https://github.com/jasonronalddavis/ProjitekFrontEnd
I have added routes to post-event data.
var keystone = require('keystone');
var Event = keystone.list('Event');
module.exports = function (req, res) {
if (!req.body.name || !req.body.startTime || !req.body.endTime) {
return res.send({ status: 'incomplete data set' });
}
var newEvent = new Event.model();
Event.updateItem(newEvent, req.body, function (error) {
res.locals.enquirySubmitted = true;
if (error) res.locals.saveError = true;
res.render('addEvent');
});
};
When I start the app I am getting below error.
if (!result) throw new ReferenceError('Unknown keystone list ' + JSON.stringify(key));
^
ReferenceError: Unknown keystone list "Events"
at Keystone.list (/Users/rigalpatel/KS_shopingcart/node_modules/keystone/lib/core/list.js:7:21)
at Object. (/Users/rigalpatel/KS_shopingcart/routes/api/event/post.js:2:22)
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 Module.require (internal/modules/cjs/loader.js:637:17)
at require (internal/modules/cjs/helpers.js:20:18)
at /Users/rigalpatel/KS_shopingcart/node_modules/keystone/lib/core/importer.js:42:23
at Array.forEach ()
at importer (/Users/rigalpatel/KS_shopingcart/node_modules/keystone/lib/core/importer.js:32:26)
at /Users/rigalpatel/KS_shopingcart/node_modules/keystone/lib/core/importer.js:36:22
at Array.forEach ()
Would you please provide your feedback. suggestion how to fix above issue.
Vesrion
Keystone 4.0.0
Node.js 10.9.0
Browser Google Chrome 69.0.3497.100
Thanks
I had this error and realized I was setting my routes before importing my models. Make sure you are importing your models before setting your routes and that your models are registered.
error comes because you have not created any Model with name Event
I am following a tutorial on how to set up a basic mvc in Nodejs using the hapi server and a few other packages.
Tutorial: https://www.sitepoint.com/node-js-mvc-application/
Git for my project: https://github.com/christoph88/node-js-mvc-tut/
I have an error when I try to launch the server:
~/Projects/node-js-mvc-tut$ node server.js
/home/christoph/Projects/node-js-mvc-tut/server.js:33
Models.sequelize.sync().then(() => {
^
TypeError: Cannot read property 'sync' of undefined
at Object.<anonymous> (/home/christoph/Projects/node-js-mvc-tut/server.js:33:17)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Function.Module.runMain (module.js:605:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:575:3
Model is defined within the requirements. I do not understand why sync is undefined. Sequelise is required within the lib/index.js file.
'use strict';
const Hapi = require('hapi');
const Hoek = require('hoek');
const Path = require('path');
const Settings = require('./settings');
const Routes = require('./lib/routes');
const Models = require('./lib/models/');
const server = new Hapi.Server();
server.connection({ port: Settings.port });
server.register([
require('vision'),
require('inert')
], (err) => {
Hoek.assert(!err, err);
server.views({
engines: { pug: require('pug') },
path: Path.join(__dirname, 'lib/views'),
compileOptions: {
pretty: false
},
isCached: Settings.env === 'production'
});
// Add routes
server.route(Routes);
});
Models.sequelize.sync().then(() => {
server.start((err) => {
Hoek.assert(!err, err);
console.log(`Server running at: ${server.info.uri}`);
});
});
Can somebody help me with this? Would be great to get this running so I can try to adapt it to my needs.
I have got it working by moving my index.js file to the models folder.
This file has the necessairy scripts that dispatches sequelise in the model thus fixing the problem.
Make sure you have exported the db in index.js
module.exports = db
and declared a db variable at the beginning of the file
var db = {}
This is my server.js code
var express = require('express');
feeds = require('./routes/whatshappeningfeed');
var http = require('http');
var pathname = require('path');
// Test services - to be removed
courses = require('./routes/courses');
auth = require('./routes/auth');
token = require('./routes/token');
var app = express();
app.configure(function () {
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser());
});
app.use(function (error, req, res, next) {
if (!error) {
next();
} else {
console.error(error.stack);
res.send(500);
}
});
app.get('/me/whatshappeningfeed',feeds.getfeeds);
app.get('/courses', courses.findAll);
app.get('/courses/:id', courses.findById);
app.get('/token', token.auth);
app.get('/auth', auth.auth);
app.get('/refresh', auth.refresh);
app.listen(80);
console.log('Listening on port 80...');
this is my error message :
F:\NODE.JS\poc\node_modules\express\lib\router\index.js:291
throw new Error(msg);
^
Error: .get() requires callback functions but got a [object Undefined]
at F:\NODE.JS\poc\node_modules\express\lib\router\index.js:291:11
at Array.forEach (native)
at Router.route (F:\NODE.JS\poc\node_modules\express\lib\router\index.js:287:13)
at Router.(anonymous function) [as get] (F:\NODE.JS\poc\node_modules\express\lib\router\index.js:318:16)
at Function.app.(anonymous function) [as get] (F:\NODE.JS\poc\node_modules\express\lib\application.js:431:26)
at Object.<anonymous> (F:\NODE.JS\poc\server.js:44:5)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
When i run the node server.js file i got above error. it was working earlier. i couldn't sort out the issue. please anyone help me.
The error says it all, app.get() requires a callback function. So it means that one or more of your routes are missing a callback.
ALL of your routes should have a function(req,res), whether explicitely as in the example or in another function (see comments) :
app.get('/me/whatshappeningfeed', function(req,res){ //request, response
//then here you can define what your server should send as a response when queries for /me/whatshappeningfeed
res.send(feeds.getfeeds()); //this will send back to the browser the result of feeds.getfeeds()
});
Also, not sure if it's due to the copypaste you did, but the first semicolon require('express'); should be a comma.
I am working to load JSON data using Node/express.js and plot it on map. As first start, I am inspired by the example presented in the repp leaflet-geojson-stream. https://github.com/tmcw/leaflet-geojson-stream/tree/master/example
Client:
https://github.com/tmcw/leaflet-geojson-stream/blob/master/example/client.js
var L = require('leaflet'),
leafletStream = require('../');
L.Icon.Default.imagePath = 'http://leafletjs.com/dist/images';
window.onload = function() {
var div = document.body.appendChild(document.createElement('div'));
div.style.cssText = 'height:500px;';
var map = L.map(div).setView([0, 0], 2);
L.tileLayer('http://a.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
var gj = L.geoJson().addTo(map);
leafletStream.ajax('/points.geojson', gj)
.on('end', function() {
});
};
Server :
https://github.com/tmcw/leaflet-geojson-stream/blob/master/example/server.js
var express = require('express'),
browserify = require('browserify'),
app = express();
app.get('/', function(req, res) {
res.send('<html><head><link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" /></head><body><script src="bundle.js"></script></html>');
});
app.get('/bundle.js', function(req, res) {
var b = browserify();
b.add('./client.js');
b.bundle().pipe(res);
});
app.get('/points.geojson', function(req, res) {
res.write('{"type":"FeatureCollection","features":[');
var i = 0, die = 0;
function send() {
if (++i > 20) {
res.write(JSON.stringify(randomFeature()) + '\n,\n');
i = 0;
} else {
// it seems like writing newlines here causes the buffer to
// flush
res.write('\n');
}
if (die++ > 1000) {
res.write(JSON.stringify(randomFeature()));
res.write(']');
res.end();
return;
}
setTimeout(send, 10);
}
send();
});
app.listen(3000);
function randomFeature() {
return {
type: 'Feature',
geometry: {
type: 'Point',
coordinates: [
(Math.random() - 0.5) * 360,
(Math.random() - 0.5) * 180
]
},
properties: {}
};
}
In the project, they create random json file. I wanted to read json file, then plot it. The reason I want to "Stream data" is to deal with the size of file (I know that there is better and easier ways to load json data), But I wanted to use this module.
I modified the server script :
var express = require('express'),
browserify = require('browserify'),
app = express();
app.get('/', function(req, res) {
res.send('<html><head><link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css" /></head><body><script src="bundle.js"></script></html>');
});
app.get('/bundle.js', function(req, res) {
var b = browserify();
b.add('./client.js');
b.bundle().pipe(res);
});
var o = require('../output_.geojson');
app.get('/points.geojson', function(req, res) {
res.json(o);
});
app.listen(3000);
res.write('');
But I am getting error :
/Users/macbook/leaflet-geojson-stream/output_.geojson:1
(function (exports, require, module, __filename, __dirname) { "type":"FeatureC
^
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 Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/macbook/leaflet-geojson-stream/example/server.js:15:9)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
Can anyone give a hint on what should I do in order to read and load json external file to plot the data.
The : isn't expected, because you're in a function at that point.
To parse JSON, you simply have to call JSON.parse(), as stated in How to parse JSON using Node.js?. So you read the file, get the JSON String that's in there, and put it through JSON.parse()
You are currently loading the whole JSON file into memory by 'requiring' it.
Instead you want to stream the file because it is big and so use the fs.createReadStream function:
var fs = require('fs');
app.get('/points.geojson', function(req, res) {
res.setHeader('Content-Type', 'application/json');
fs.createReadStream(__dirname + '../output_.geojson').pipe(res);
});
Also make sure that the contents of ../output_.geojson is actually valid JSON. You can use JSONLint to check - the file should with '{' or '[' and NOT have Javascript functions inside.