Node Error - Cannot read property of undefined [closed] - node.js

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm attempting to write a node module that works with a node package. I'm kind of stuck, and don't know where the problem is. I know the package is being loaded correctly.
The Code Below is referencing the icontrol package
https://github.com/nfarina/icontrol/blob/master/index.js
// loads the icontrol package
var iControl = require("node-icontrol").iControl;
// these are the paramters you need
// according to this https://github.com/nfarina/icontrol/blob/master/index.js#L19-L22
var config = {
system: "system name",
email: "your#email.com",
password: "kdkdkdkdk",
pinCode: "pin"
}
// then you will want to initialize it
var mySystem = iControl(config);
// then there are a few calls you can make on mySystem
// 1. getArmState https://github.com/nfarina/icontrol/blob/master/index.js#L56
mySystem.getArmState(function(error, result){
if (error) {
console.error(error);
return
}
console.log(result);
});
// 2. setArmState https://github.com/nfarina/icontrol/blob/master/index.js#L70
// it looks like the armState param can be "disarm" or "arm"
mySystem.setArmState(armState, function(error){
if (error) {
console.error(error);
return
}
console.log("Alarm set to:", armState);
});
// 3. subscribeEvents https://github.com/nfarina/icontrol/blob/master/index.js#L96
// this will open a web socket listener that will send a message any
// time the arm state is changed
Error I'm receiving
mySystem.getArmState(function(error, result){
^
TypeError: Cannot read property 'getArmState' of undefined
at Object.<anonymous> (/Users/Admin/Documents/Test.js:15:9)
at Module._compile (module.js:425:26)
at Object.Module._extensions..js (module.js:432:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:313:12)
at Function.Module.runMain (module.js:457:10)
at startup (node.js:138:18)
at node.js:974:3
can anyone help ?

You forgot the new operator. The iControl function is meant to be used as a constructor (with new). It doesn't have an explicit return statement, so without new it returns undefined.
Change:
var mySystem = iControl(config);
To:
var mySystem = new iControl(config);

Related

throw new TypeError('2nd argument to `Model` must be a POJO or string, ' + [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
i just created my node js server and when i specified the schema and model and added it ins the main server file it is showing following error:
E:\py\.vscode\mern stack\backend\node_modules\mongoose\lib\model.js:115
throw new TypeError('2nd argument to `Model` must be a POJO or string, ' +
^
TypeError: 2nd argument to `Model` must be a POJO or string, **not** a schema. Make sure you're calling `mongoose.model()`, not `mongoose.Model()`.
at Mongoose.Model (E:\py\.vscode\mern stack\backend\node_modules\mongoose\lib\model.js:115:11)
at Object.<anonymous> (E:\py\.vscode\mern stack\backend\user.js:7:27)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Module.require (node:internal/modules/cjs/loader:1005:19)
at require (node:internal/modules/cjs/helpers:102:18)
at Object.<anonymous> (E:\py\.vscode\mern stack\backend\server.js:2:14)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
and the code of schema and model is as given below:
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
email: String,
password: String
})
module.exports = mongoose.Model('USER', userSchema);
just write mongoose.model instead of mongoose.Model. I hope problem will be solved.

Why do I get this error TypeError: Cannot read property 'utf8Slice' of undefined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have no prior knowledge about backend related codes and all so I decided to start recent to learn a few things gradually so I decided to follow a tutorial and now I'm stuck with an error I've researched but cannot still fix.
I have this
const postsSchema = require('./posts')
const resolvers = [
postsSchema.resolvers
]
const typeDefs = [
postsSchema.schema
]
module.exports = {
resolvers,
typeDefs
}
const trendingPosts = require('./mocks/trending')
const featuredPosts = require('./mocks/featured')
const fs = require('fs')
const path = require('path')
module.exports = {
resolvers: {
Query: {
trendingPosts: () => trendingPosts,
featuredPosts: () => featuredPosts,
recentPosts: () => [
...trendingPosts,
...featuredPosts,
...featuredPosts
]
}
},
schema: fs.readFileSync(
path.resolve(
__dirname,
'./posts-schema.graphql'
)
).toString
}
This is my GraphQl
type Query {
trendingPosts: [Post]!
featuredPosts: [Post]!
recentPosts: [Post]!
}
type Post {
id: Int,
title: String
date: String
categories: [String]
author: String
description: String
image: String
}
I'm quite sure I followed the whole process in the tutorial but when I run node app, I get this error in the terminal
buffer.js:778
return this.utf8Slice(0, this.length);
^
TypeError: Cannot read property 'utf8Slice' of undefined
at toString (buffer.js:778:17)
at C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:195:65
at Array.forEach (<anonymous>)
at concatenateTypeDefs (C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:191:24)
at buildDocumentFromTypeDefinitions (C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:231:46)
at buildSchemaFromTypeDefinitions (C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:213:22)
at makeExecutableSchema (C:\Users\Natey\Desktop\Code Related\my-app\graphql\node_modules\#graphql-tools\schema\index.cjs.js:811:32)
at Object.<anonymous> (C:\Users\Natey\Desktop\Code Related\my-app\graphql\app.js:8:13)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
I need help please, I'll really appreciate it.
As #pzaenger pointed out .toString should be .toString()
Edit:
The key here is to learn to read your stack traces.
buffer.js:778 // This is a node module
return this.utf8Slice(0, this.length);
^
TypeError: Cannot read property 'utf8Slice' of undefined // This is sort of helpful, it's telling use something is trying to access a function utf8Slice of undefined
at toString (buffer.js:778:17) // buffer.js is trying to access utf8Slice on a this object at `toString`
// So now we know a buffer is trying to call utf8Slice on an undefined `this`
// at `toString`. Taking a quick look at your code we see fs.readFileSync(...)
// which gives us a buffer back and then `fs.readFileSync(...).toString`
// experince tells us that toString is a function not a property

Read file and write file JSON

In this, I am trying to make a hit counter where every time someone visits my site the variable will be read from the views.json file one is added to the number and then the .json will be updated with the new number. However when I tested it in a repl.it project I got an error saying
ReferenceError: writeFileSync is not defined
at /home/runner/hit-counter/index.js:6:1
at Script.runInContext (vm.js:133:20)
at Object.<anonymous> (/run_dir/interp.js:156: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)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
I don't know what this means if you know please tell me and how I may be able to fix it.
the reply project link:https://hit-counter.cohense.repl.run/
The JavaScript (ES6)
const fs = require('fs');
let views = fs.readFileSync('views.json');
views = JSON.parse(views);
views.total++;
let data = JSON.stringify(views, null, 2);
writeFileSync("views.json", data, finished);
function finished(err) {
if (views = JSON.parse(views)) {
console.log("Your view has been accounted for!")
} else {
console.error("Error occured please reload the page =(")
}
};
the JSON
{
"totalViews": 1
}
You can do like this, just fixed some errors.
Oh, you should use writeFileSync, to avoid that the file will not be edited at same time.
The question is, why don't you use a DB? It's a lot faster and fix concurrency writes.
var fs = require('fs')
var data = fs.readFileSync('views.json')
var views = JSON.parse(data);
console.log(views);
views.total = views.total + 1;
var data = JSON.stringify(views, null, 2)
writeFileSync("views.json", data, ()=>{
console.log("Your View Has Been Accounted For!")
})
I found out what I did wrong I didn't use fs.
writeFileSync("views.json", data, finished);
When I just needed to do
fs.writeFileSync("views.json", data[,finished]);

mongodb with nodejs

this is th code I am using inserting a document to mongodb.
var client = new Db('test', new Server("127.0.0.1", 27017, {}), {w: 1}),
test = function (err, collection) {
collection.insert({a:2}, function(err, docs) {
collection.count(function(err, count) {
test.assertEquals(1, count);
});
// Locate all the entries using find
collection.find().toArray(function(err, results) {
test.assertEquals(1, results.length);
test.assertTrue(results[0].a === 2);
// Let's close the db
client.close();
});
});
};
client.open(function(err, p_client) {
client.collection('test_insert', test);
});
but while running I am getting error
xports, require, module, __filename, __dirname) { var client = new Db('test',
^
ReferenceError: Db is not defined
at Object. (C:\Users\Basic node\cheerio\mongonode.js:1:81
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)
can you suggest me how to solve this problem
thanks in advance
Please import all the required modules, which you are using. Db is not defined points out that Db is defined in some other module or you have forgot to declare it.
You'll notice this exact code block posted in a number of different stackoverflow questions. The problem here is that this is a copy and pasted code block from mongodb's documentation, as is in fact the first example of a mongodb nodejs program.
https://npmjs.org/package/mongodb
You'll find this under "Introduction" as "A simple example of inserting a document."
It's clearly an incomplete example, but a lot of people are just trying it out to see if they've got everything installed correctly and immediately run into a wall.
Most people will have installed the mongodb driver, but will be missing something at the top like this:
var mongodb = require('mongodb');
var Db = mongodb.Db;
var Server = mongodb.Server;
I also fell into the copy-paste trap here and ran into another issue with the "assertEquals" method not existing. I've seen other people reference that function in other places on the web, but not really sure how it works.
In any case, to make it work for me, I required the assert module:
var assert = require('assert');
And then I replaced the assertEquals lines with something like this:
assert.equal(1, count, "Unexpected result");
Note that you're going to run into an issue if you've run this a couple of times; it's going to count the number of things in that table, and there is going to be more than one.
You'll have to figure out how to get into mongo's CLI and remove them to get it to run successfully.
Try to install mongodb native driver
npm install mongodb

Creating temporary view in couchdb using node-couchdb-api

I am trying to connect couchdb using node-couchdb-api at nodejs level as mentioned in the following link http://dominicbarnes.us/node-couchdb-api/.My couchdb version is 1.1.1 and nodejs version is 0.6.10.
For creating temporary view as mentioned in api http://dominicbarnes.us/node-couchdb-api/api/database/tempView.html I have written the following code.
var couchdb = require("couchdb-api");
var server = couchdb.srv(localhost, 5984, false, false);
var db = server.db("test");
var map = function (doc) {
emit(null, 1);
};
var reduce = "_sum";
var query = { include_docs: true };
db.tempView(map, reduce, query, function (err, response) {
console.log(response);
});
But i am facing the following problem.
C:\Program Files\nodejs\node_modules\couchdb-api>node server.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
TypeError: Cannot read property '0' of null
at C:\Program Files\nodejs\node_modules\couchdb-api\lib\util.js:24:39
at Array.map (native)
at Object.formatFunction (C:\Program Files\nodejs\node_modules\couchdb-api\lib\util.js:22:25)
at Object.tempView (C:\Program Files\nodejs\node_modules\couchdb-api\lib\database.js:285:28)
at Object.<anonymous> (C:\Program Files\nodejs\node_modules\couchdb-api\server.js:27:4)
at Module._compile (module.js:441:26)
at Object..js (module.js:459:10)
at Module.load (module.js:348:31)
at Function._load (module.js:308:12)
at Array.0 (module.js:479:10)
please suggest me to resolve the issue.
Thanks in advance.
sorry about the problem you were experiencing. I'm the creator of that module, and I've just pushed version 1.1.2 up to NPM which addresses your problem. (and includes a unit test to make sure it doesn't happen again)
Just update to the latest version via npm update couchdb-api and you should be set to go. Let me know if you have further issues.

Resources