Node fsmkdirSync error - javascript

I have the following folder structure:
Inside of CacheModule.js i have the following code:
socket.on('saveUserCache', function (obj, user_id) {
var jsonOutput = JSON.stringify(obj);
if (!fs.existsSync('./cacheObjects/' + user_id)) {
fs.mkdirSync('./cacheObjects/' + user_id, 0777, function (err) {
if (err) {
console.log(err);
}
});
}
fs.writeFile('./cacheObjects/' + user_id + '/cache.json', jsonOutput, function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
});
The idea behind this is to check if the users folder exists (if not) create a new folder and then write to a file.
However im getting the following error:
Error: ENOENT: no such file or directory, mkdir './cacheObjects/125'
at Error (native)
at Object.fs.mkdirSync (fs.js:794:18)
at Socket.<anonymous> (/var/www/project/app_server/costum_modules/CacheModule.js:10:16)
at emitTwo (events.js:87:13)
at Socket.emit (events.js:172:7)
at Socket.onevent (/var/www/project/app_server/node_modules/socket.io/lib/socket.js:330:8)
at Socket.onpacket (/var/www/project/app_server/node_modules/socket.io/lib/socket.js:290:12)
at Client.ondecoded (/var/www/project/app_server/node_modules/socket.io/lib/client.js:193:14)
at Decoder.Emitter.emit (/var/www/project/app_server/node_modules/socket.io/node_modules/socket.io-parser/node_modules/component-emitter/index.js:134:20)
at Decoder.add (/var/www/project/app_server/node_modules/socket.io/node_modules/socket.io-parser/index.js:247:12)
at Client.ondata (/var/www/project/app_server/node_modules/socket.io/lib/client.js:175:18)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at Socket.onPacket (/var/www/project/app_server/node_modules/socket.io/node_modules/engine.io/lib/socket.js:99:14)
at emitOne (events.js:82:20)
at WebSocket.emit (events.js:169:7)
Can anyone tell me why this is happening. it looks like its sending mkdir with the string. Also i have given the right permissions (so it is not lacking permissions)

Related

Node.js 'request' unhandled error, node:events:368

I'm getting a reoccuring error that crashes my program.
In the program, I'm consistantly making async requests (one by one I should say)
to download specific images off the internet, this is my code for the request:
const urlDownload = (uri, filename, callback) => {
try {
console.log('start url');
console.log(uri);
request.head(uri, function(err, res, body){
if(err) {
console.log('request error!');
console.log(err);
} else {
request(uri).pipe(fs.createWriteStream(filename)).on('close', callback);
console.log('end url');
}
// console.log('content-type:', res.headers['content-type']);
// console.log('content-length:', res.headers['content-length']);
});
} catch(e) {
console.log('urlDownload issue');
console.log(e);
}
}
Now, sometimes it doesn't crash, but I feel like 50% or more of the times it does with this exact error:
node:events:368
throw er; // Unhandled 'error' event
^
Error: aborted
at connResetException (node:internal/errors:691:14)
at TLSSocket.socketCloseListener (node:_http_client:407:19)
at TLSSocket.emit (node:events:402:35)
at node:net:687:12
at TCP.done (node:_tls_wrap:580:7)
Emitted 'error' event on Request instance at:
at Request.onerror (node:internal/streams/legacy:62:12)
at Request.emit (node:events:390:28)
at IncomingMessage.<anonymous> (/home/mrz/Desktop/DEVELOPMENT/node_modules/request/request.js:1079:12)
at IncomingMessage.emit (node:events:390:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'ECONNRESET'
}
I don't know what to do, tried to search about it and found nothing really,
nothing wrong with the URL it tries to download too!
based on the console logs I have made, it seems like it crashes AFTER it ends the request process successfully I think, because I do get the output, and then it crashes, that's just speculations, I have no idea what's going on.

Run python script using node js error no 22

I'm using node.js to run a python script through the web browser. below is the ScriptRunner.js code.
var PythonShell = require('python-shell');
var path = require('path');
exports.runScript = function() {
var options = {
scriptPath: 'D:\L4Project\working code\finalproject\routes'
};
PythonShell.run('sensitive2.py',options, function (err, results) {
if (err) throw err;
console.log('results: %j', results);
});
}
when I run the script in browser it returns error message like below.
D:\L4Project\working code\finalproject\routes\scriptRunner.js:10
if (err) throw err;
^
outes\sensitive2.py': [Errno 22] Invalid argumentg codeinalproject at PythonShell.parseError (D:\L4Project\working code\finalproject\node_modules\python-shell\index.js:191:17)
at terminateIfNeeded (D:\L4Project\working code\finalproject\node_modules\python-shell\index.js:98:28)
at ChildProcess.<anonymous> (D:\L4Project\working code\finalproject\node_modules\python-shell\index.js:89:9)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
I have googles lot and nothing worked. Can Somebody help me to solve the problem?

How to connect Mongo Atlas Database in Lambda function with Mongoose

I am using Serverless framework to deploy my backend to API Gateway and AWS Lambda.
Here is my serverless.yml for this specific lambda function.
It is a cron job that runs every hour.
cron:
handler: handler.transferHandler
events:
- schedule: rate(1 hour)
Now when I test on localhost it works perfectly. But when I deploy to aws I get the following error:
MongoDB connection error. Please make sure MongoDb is running. { MongoError: failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]
at Pool.<anonymous> (/var/task/node_modules/mongodb-core/lib/topologies/server.js:336:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/pool.js:280:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/connection.js:189:49)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at connectErrorNT (net.js:1021:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
name: 'MongoError',
message: 'failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]' }
Here is my function in my handler.js:
exports.transferHandler = function transferHandler(event, context) {
context.callbackWaitsForEmptyEventLoop = false;
mongoose.connect(mongoString, {useMongoClient: true});
const db = mongoose.connection;
db.on("error", (err) => {
console.log("MongoDB connection error. Please make sure MongoDb is running.", err);
process.exit();
});
db.once('open', () => {
BookingModel
.find({})
.then((bookings) => {
...
})
.catch((err) => {
console.log(err);
})
.finally(() => {
db.close();
});
});
};
After 2 weeks of being stuck on this, I learned that I needed to specify my environment variables in my serverless.yml for it to work. My functions were never connecting to the database because my mongo string was never set in lambda. Hope this helps someone.
provider:
name: aws
runtime: nodejs6.10
stage: production
region: us-west-1
environment:
MONGODB_URL: ${env:MONGODB_URL}
S3_BUCKET: ${env:S3_BUCKET}
S3_BUCKET_REPORT: ${env:S3_BUCKET_REPORT}
STRIPE_CLIENT_ID: ${env:STRIPE_CLIENT_ID}
STRIPE_PUBLIC_KEY: ${env:STRIPE_PUBLIC_KEY}
STRIPE_SECERET_KEY: ${env:STRIPE_SECERET_KEY}
JWT_SECRET: ${env:JWT_SECRET}
SEND_BIRD_TOKEN: ${env:SEND_BIRD_TOKEN}
SEND_BIRD_APP_ID: ${env:SEND_BIRD_APP_ID}
MANDRILL_APIKEY: ${env:MANDRILL_APIKEY}

Importing data from firebase to bigquery

I'm trying to import data from firebase to big query upon onWrite event and getting same error each time function is triggered given below.
PartialFailureError: A failure occurred during this request.
at /user_code/node_modules/#google-cloud/bigquery/src/table.js:1086:13
at Object.handleResp (/user_code/node_modules/#google-cloud/bigquery/node_modules/#google-cloud/common/src/util.js:134:3)
at /user_code/node_modules/#google-cloud/bigquery/node_modules/#google-cloud/common/src/util.js:465:12
at Request.onResponse [as _callback] (/user_code/node_modules/#google-cloud/bigquery/node_modules/retry-request/index.js:120:7)
at Request.self.callback (/user_code/node_modules/#google-cloud/bigquery/node_modules/request/request.js:188:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request. (/user_code/node_modules/#google-cloud/bigquery/node_modules/request/request.js:1171:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
my function code is
exports.addtobigquery = functions.database.ref('/mn_users').onWrite(event =>
{
const dataset = bigquery.dataset(functions.config().bigquery.datasetname);
const table = dataset.table(functions.config().bigquery.tablename);
return table.insert({
id: event.data.key,
name: event.data.val().name,
email: event.data.val().email
});
});
I want to figure out what I'm doing wrong?

Error 401 in windows command prompt?

When use npm run dev, which scripts the "node app.js" to run. But when I try to run it, I get this error code:
C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter>npm run dev
> Tweeter#1.0.0 dev C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter
> node app.js
Error: Status Code: 401
at Request.<anonymous (C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter\node_modules\twitter\lib\twitte
r.js:274:28)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at Request.onRequestResponse (C:\Users\rfasc\Dropbox\Hackathon\HackCuTwitter\node_modules\request\request.js:
1074:10)
at emitOne (events.js:96:13)
at ClientRequest.emit (events.js:188:7)
at HTTPParser.parserOnIncomingClient [as onIncoming]
(_http_client.js:473:21)
at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
at TLSSocket.socketOnData (_http_client.js:362:20)
at emitOne (events.js:96:13)
I also get this error when I try to run sudo at all when I use bash in the cmd:
ryryfasch#LAPTOP-9TPB1OJ6:/mnt/c/Users/rfasc/Dropbox/Hackathon/HackCuTwitter$ sudo i
sudo: unable to resolve host LAPTOP-9TPB1OJ6
I have tried looking up many fixes and can't figure it out. Thanks.
Here is my app.js file:
var twitterpack = require('twitter');
var tokens = {
consumer_key: '----------SaaqAe9yVvr30CF',
consumer_secret: '---------------oK7Dfj3zoiZ2nUOTBWUjP4DqtGXIlzzbxbOY',
token_key: ' -----------------3N6RZJeOtJeH8ZhrursJUQlAqCycHqxbl',
token_secret: '---------------2QYwSSZStETF7Mr2mBikHYCTTqodV'
}
var Twitter = new twitterpack(tokens);
Twitter.stream('statuses/filter', {track: 'hey'}, function(stream) {
stream.on('data', function(stream){
console.log(tweet.text);
var meanReply = {status: "hey #" + tweet.user.screen_name}
Twitter.post('statuses/update', meanReply, function(error, tweetReply, response){
if(error) {console.log(error) /*&&db.collection('errors', error.text)*/};
console.log(tweetReply.text)}
);
});
stream.on('error', function(error) {
console.log(error);
});
});

Categories