Why do I get this error TypeError: Cannot read property 'utf8Slice' 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 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

Related

How to remove TypeError: "x" is not a function?

I am trying to learn how to make a discord bot and pull data from this API called Ergast (http://ergast.com/mrd). I found this npm (https://github.com/estevE11/f1-stats) which uses NodeJS implementation to get a historical record of F1 data from Ergast API. Sorry for the bad wording I am still trying to learn the lingo.
I followed what was stated in the npm documentation for installing it and tried using the example to get data from the API. However when I run the code in index.js I get the error "TypeError: "x" is not a function". When I go into the node_modules "f1-stats" folder and run the code from main.js I do get the correct result.
index.js:
const client = new Discord.Client(); //This will be our client
const { prefix, token } = require('./config.json');//const PREFIX = '!';
const f1s = require('f1-stats');
//module.exports.f1s = f1s; //Still causes the TypeError
f1s("2008 drivers", (res) => {
console.log(res);
});
The error message I get in index.js:
f1s("2008 drivers", (res) => {
^
TypeError: f1s is not a function
at Object.<anonymous> (C:\Users\RyanPC\Documents\DiscordBot\index.js:8:1)
at Module._compile (internal/modules/cjs/loader.js:776:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
node_modules/f1-stats/main.js:
const f1s = require("./f1-stats"); // "./" is used because module is located in the same folder as the Node.js file
f1s("2008 drivers", (res) => {
console.log(res);
});
when I run it in node_modules/f1-stats/main.js:
{ MRData:
{ xmlns: 'http://ergast.com/mrd/1.4',
series: 'f1',
url: 'http://ergast.com/api/f1/2008/drivers.json',
limit: '30',
offset: '0',
total: '22',
DriverTable: { season: '2008', Drivers: [Array] } } }
Because f1-stats doesn't export anything so when you import it. It is empty. The correct file you need to import is f1-stats/f1-stats.
const f1s = require('f1-stats/f1-stats');
try importing f1s properly , you are getting error because you have not imported the function properly , in other words...check what is being exported from what are you trying to import....hope it solves the problem.

Type Error: Cannot read property 'hasListCollectionsCommand' of null

I'm trying to get all collection names in mongodb (v4.0.2) and using mongodb#3.1.10 nodejs driver. From the docs, I can see that listCollections might work, but running the following:
const Db = require('mongodb').Db
const Server = require('mongodb').Server
const db = new Db(dbName, new Server(host, port, options), {})
db.listCollections().toArray((error, collectionNames) => {
console.error(error)
console.log(JSON.stringify(collectionNames))
})
… leads to this error:
if (this.serverConfig.capabilities().hasListCollectionsCommand) {
TypeError: Cannot read property 'hasListCollectionsCommand' of null
at Db.listCollections ({path}/node_modules/mongodb/lib/db.js:493:39)
at db.createCollection ({path}/sampleMongoDB.js:19:8)
at err ({path}/node_modules/mongodb/lib/utils.js:415:14)
at executeCallback ({path}/node_modules/mongodb/lib/utils.js:404:25)
at executeOperation ({path}/node_modules/mongodb/lib/utils.js:422:7)
at Db. ({path}/node_modules/mongodb/lib/db.js:431:12)
at Db.deprecated [as createCollection] ({path}/node_modules/mongodb /lib/utils.js:661:17)
at Object.< anonymous > ({path}/sampleMongoDB.js:18:6)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
My questions are:
Is there a docs site for MongoDB NodeJs drivers where we can refer examples from?
If not, what's the correct way to query?
I was able to work it out. The MongoClient's instance returns a db instance, which inturn helps run mongodb.Db methods.
Here's a sample code that worked (Ref. to MongoDB guides)
const options = {
useNewUrlParser: true, // Add this, if you wish to avoid {https://stackoverflow.com/questions/50448272/avoid-current-url-string-parser-is-deprecated-warning-by-setting-usenewurlpars} issue
}
const client = new MongoClient(connectionUri, options)
return client.connect().then(() => {
const db = client.db(dbName)
return db.listCollections()
.toArray()
.then((collections) => {
// Collections array
})
})
#Community mods - if required, kindly close this question.

bluebird npm TypeError: Cannot read property 'call' of null

I am using bluebird npm,I am getting the above error
I am calling three different function & doing some database operation, but I am getting this error.
If I tried with two functions, it is working but with three function it is throwing error, TypeError: Cannot read property 'call' of null.
If you go to bluebird/js/release/using.js and comment the line no 39 ;
If I comment this line, then this issue is not coming & all is working fine.
If you want more info please Click Here
This is main.js
var myModule = require('../lib/myModule');
var sync = require('deasync');
var id = 90;
var moduleObj = new moduleEntity(id);
console.log(moduleObj);
var id = 90;
var moduleObj = new moduleEntity(id);
console.log(moduleObj);
var id = 90;
var moduleObj = new moduleEntity(id);
console.log(moduleObj);
In MyModule.js
var deasync = require('deasync');
var dbEntity = require('../db/dbEntity');
module.exports = function (id) {
var outputEntity;
dbEntity(id, function(data){
outputEntity = data
});
while(outputEntity === undefined) { deasync.runLoopOnce();};
return outputEntity;
};
In dbEntery.js
var Promise = require("bluebird");
var getConnection = require('./dbcon');
module.exports = function (id,cb) {
var sql_getRecords = SELECT * from tanle_name;
Promise.using(getConnection, function (conn) {
return conn.query(sql_getRecords).then(function(data){
cb(data[0]);
})
});
};
Here is error stack trace
TypeError: Cannot read property 'call' of null
at FunctionDisposer.doDispose (/home/user/Projects/project_name/node_modules/bluebird/js/release/using.js:98:18)
at FunctionDisposer.Disposer.tryDispose (/home/user/Projects/project_name/node_modules/bluebird/js/release/using.js:78:20)
at iterator (/home/user/Projects/project_name/node_modules/bluebird/js/release/using.js:36:53)
at dispose (/home/user/Projects/project_name/node_modules/bluebird/js/release/using.js:48:9)
at /home/user/Projects/project_name/node_modules/bluebird/js/release/using.js:194:20
at PassThroughHandlerContext.finallyHandler (/home/user/Projects/project_name/node_modules/bluebird/js/release/finally.js:55:23)
at PassThroughHandlerContext.tryCatcher (/home/user/Projects/project_name/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/user/Projects/project_name/node_modules/bluebird/js/release/promise.js:510:31)
at Promise._settlePromise (/home/user/Projects/project_name/node_modules/bluebird/js/release/promise.js:567:18)
at Promise._settlePromise0 (/home/user/Projects/project_name/node_modules/bluebird/js/release/promise.js:612:10)
at Promise._settlePromises (/home/user/Projects/project_name/node_modules/bluebird/js/release/promise.js:687:18)
at Async._drainQueue (/home/user/Projects/project_name/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/home/user/Projects/project_name/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/home/user/Projects/project_name/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:651:20)
at tryOnImmediate (timers.js:624:5)
Bluebird version -- 3.5
Node Version -- v7.6.0
You provided no code examples so it's hard to give you any detailed answer but here are some things that you have to keep in mind when you get error like this.
TypeError: Cannot read property 'call' of null means that some code (also impossible to tell you which code because you didn't provide an example and full error stack trace) tries to bind some function to some this object and arguments using Function.prototype.call() - see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
but instead of the function it got null.
Now you need to follow the stack trace and see which code is trying to call the function and where the null originated to fix your problem.
Note that it is null and not undefined so it must have been provided explicitly instead of just being a missing argument to a function call or a missing property on an object. This is an important hint that should let you diagnose the problem much easier.

Cannot read property 'get' of undefined for unit testing in mocha [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 6 years ago.
Improve this question
I am trying to write a unit test over my file routes.js using mocha and chai. I have defined a function in routes.js and has defined a test file in which my test case is there.
When i am running my test case, its showing the error TypeError: Cannot read property 'get' of undefined
My code for test.js is
var expect = require('chai').expect;
var chai = require('chai');
var app = ('../api/smartAccount/identifyLoan/getDirectDebitTrans/routes');
describe("Unit testing for function", function(){
it("Testing the function using mocha", function(done){
var req = {
queryString: 101
};
var test = app.getUser.get(req);
expect(test).to.be.an('undefined');
done();
});
});
I am passing req as i am expecting req.queryString.id in my routes.js .
code of routes.js is
var config = require("../../../../serverConfig/config");
module.exports = {
getUser: {
get: function(req, parameters, environment) {
var id = req.queryString.id;
//functionality
});
}
}
Please help where i am going wrong.
p.s get function is fetching data from DB but i havent mentioned the bd connection as i feel its of irrelevance here.
TIA
Nothing scary here. You are missing the require keyword in test.js's
var app = ('../api/smartAccount/identifyLoan/getDirectDebitTrans/routes');
Hence;
var expect = require('chai').expect;
var chai = require('chai');
var app = require('../api/smartAccount/identifyLoan/getDirectDebitTrans/routes');
Will fix it.
Without the require keyword, variable app is just a string with value of ../api/smartAccount/identifyLoan/getDirectDebitTrans/routes' and the code dies when it tries to access the non-existence get property. And this is evidently shown in your error message TypeError: Cannot read property 'get' of undefined

Node Error - Cannot read property 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 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);

Resources