FAQ Database Discussion Community


javascript “this” keyword works as expected in browser but not in node.js

javascript,node.js
I know I'm making a mistake here but I can't figure out what it is. The following code (non-strict mode) works as I expect in a browser and outputs "hello" to the console. function a() { console.log(this.bar); } var bar = "hello"; a(); But when I run it in node...

Loading images into html5 canvas

javascript,node.js,image,html5-canvas,sails.js
I am using nodejs sails for my app. The app is going to use 50-100 images at some points. I was wondering if someone can point pro and cons of using /assests/images/ folder vs outside repository i.e. AWS S3 for image storing and pulling to draw on the canvas.

express.js 4: catch bodyParser error in router's errorHandler

node.js,express,body-parser
How can I catch a bodyParser error in a router's errorHandler in express.js 4? Example code: var express = require('express'); var bodyParser = require('body-parser'); var app = express(); // use bodyParser.json() app.use(bodyParser.json()); // setup route /test var testRouter = express.Router(); testRouter.post('/', function(req, res, next) { next(new Error('not implemented')); }); testRouter.use('/',...

node.js winston logger no colors with nohup

node.js,logging,nohup,winston
We are using winston logger in our project with the following transport settings: file: { filename: __base + '/log/server.log', colorize : true, timestamp : true, json : false, prettyPrint : true } If the application is started with nohup, log file is not colorized. It works only without nohup. nohup...

call functions in async with node which is more recomended Q or callback

javascript,node.js,callback,promise,q
I've node app with function that inside call to to other two function,I want to use some async behavior for it,what is recommended to use in this case. example will be very helpful. function myFunction(req,res){ //from here this is the first place which I want to use warp in function...

Socket.io client does not connect to server

node.js,express,socket.io
I am trying to make a Node.js app that will have an embedded chat. I am using socket.io to create that chat. I have attempted to set up my server / client, but the client does not seem to be connecting. I have my application to set log when sockets...

Nodejs real time pull Stream Instagram photo via hashtag

javascript,node.js,instagram-api
Is there a way / node lib package that can do real time pull instagram photo via hashtag?

nodejs Kue job processing logic

node.js,redis,kue
I have a very simple logical question. I will be running job processing logic on a separate app server. My job processing app will be a standalone app, doing nothing just processing jobs. In my code, how do I make sure that my app continuously keep checking redis server for...

Access Node-Webkit App from other Application

node.js,node-webkit
Is it possible to call a function in nodewebkit from an external application? For example. I would like to decide whether the window is hidden or show through a external application or with applescript. ...

Invoice number in create_with_paypal node sdk PayPal

node.js,paypal,sails.js,paypal-sdk
I'm using Create PayPal SDK to make a transaction using paypal and redirecting the user to paypal. I'm using the same code as per suggested in above link, but i want to send invoice number with create paypal to be shown under transaction detail. but i am not able to...

how can I import a file in node.js?

javascript,node.js
I have developed a node.js application and performing some validation with the use of a template. At the moment this 'template' is a local variable but I would like to store this in a file in my project. So this is the validation code: isvalid(req.body,template , function(err, validObj) { if...

npm install error not installing BrowserSync package

node.js,cmd,npm,command-prompt,browser-sync
Trying to install BrowserSync I've followed the steps to install the package through the command line, installed node.js and then I went on to install npm through the command line. Now when I try to install browser-sync with the following line npm install -g browser-sync you will see it is...

Node.d.ts issues errors using typescript compiler, how do I fix?

node.js,visual-studio,typescript,jasmine,protractor
I have a project that's a NODE console application project using Visual Studio 2013. When I compile the solution I'm getting typescript errors as follows: Typescript wants a semicolon after export interface ReadableStream extends EventEmitter { readable: boolean; read(size?: number): string|Buffer; //Like this ----> read(size?: number): string;|Buffer; Which means I...

Replace nodejs for python?

python,node.js,webserver
i'm working in a HTML5 multiplayer game, and i need a server to sync player's movement, chat, battles, etc. So I'm looking for ways to use python instead nodejs, because i have I have more familiarity with python. The server is simple: var express = require('express'); var app = express();...

res.send and res.render calls

javascript,node.js,express
I am trying to determine if i can call res.send(data) and then res.render('reports') simultaneously. To explain further in detail, when i route to '/reports', first on my server side i making a REST call to an API which returns back json data. Now i want this json data to be...

Error handling when uploading file using multer with expressjs

node.js,express,multer,busboy
I am using multer to save the file on server developed through express & nodejs. I am usign following code. var express = require('express'), multer = require('multer') var app = express() app.get('/', function(req, res){ res.send('hello world'); }); app.post('/upload',[ multer({ dest: './uploads/'}), function(req, res){ res.status(204).end() }]); app.listen(3000); Multer saves the file...

Storing user submitted images

node.js,file-upload,amazon-s3,amazon-cloudfront
I'm building a node application in which users can submit images to customize their profile. I'm wondering what the best way would be to store these images? Is something like Amazon S3 the way to go? What about CloudFront, can this accept user submitted images? Sorry if this question is...

Why I got so many connection events on Node's HTTP server?

javascript,node.js,http,websocket,socket.io
I have a web application using socket.io. It runs on localhost:8000 on my local machine. In order to find an annoying resource leak in my application, I tried to log out the connection events on my HTTP server: server.on('connection', function(conn) { //log out connection details }); When I open the...

Socket.IO server not receiving message from client

node.js,socket.io,mocha,bdd,expect.js
I'm playing around with Node, Socket.IO and BDD by creating a chat application. During one of the tests, I get a timeout error stating: Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test. The affected test is it('#must be able to receive a message',...

Using the shell provided with NodeJS

javascript,node.js,shell,require,node-modules
Once you've installed NodeJS, you'll have a executable in your computer named NodeJS which is a shell. I was wondering what can I do with that... here you're able to run JS code as, for example, in the browser's console, great. Now, is it possible to require modules in that...

“Arguments to path.resolve must be strings” when calling 'gitbook build' from a Git hook

node.js,git,gruntjs,githooks,gitbook
I am trying to run gitbook build within a post-receive Git hook on my (Gitlab, Debian 7, virtual private) server. Basically I want to: checkout the bare repository to a temporary dir run gitbook build in that temporary dir sync with the webspace through rsync The post-receive script runs something...

Delete multiple couchbase entities having common key pattern

node.js,couchbase,couchbase-nodejs-sdk,bulk-delete
I have a use case where I have to remove a subset of entities stored in couchbase, e.g. removing all entities with keys starting with "pii_". I am using NodeJS SDK but there is only one remove method which takes one key at a time: http://docs.couchbase.com/sdk-api/couchbase-node-client-2.0.0/Bucket.html#remove In some cases thousands...

nodejs head request isn't triggering events

node.js,http
Here's my code: var http = require('http'); var req = http.request( { host: 'example.com', method: 'HEAD', path: '/' }, function(res){ res.on('end',function(){ console.log('Ended'); }); res.on('finish',function(){ console.log('Finished'); }); res.on('close',function(){ console.log('Closed'); }); } ); req.end(); Strange thing about it is that it doesn't print anything. Takes longer than expected and exits. Is this...

Using TypeScript type definitions with Webstorm 10 [duplicate]

node.js,typescript,webstorm
This question already has an answer here: intellisense and code complete for DefinitelyTyped (TypeScript type definitions) on WebStorm IDE 2 answers I am trying to use Webstorm 10's new built-in TypeScript compiler. When compiling a simple Node.js file such as below, it gives a TS compilation error of "Error:(1,...

Is express similar to grunt? what is the difference? what are the advantages of express over grunt?

node.js,express,gruntjs,mean-stack
I've been working on node,grunt,bower and yeoman from couple of months. I came across MEAN stack applications, in which expressjs is providing the server environment(my understanding). Are both grunt and express similar? Requesting for some helpful link on express and MEAN stack. ...

Get local json file using request-promise

javascript,json,angularjs,node.js,express
I'm making a node/express app and am querying a test json file using npm request-promise. Node is spitting out the following error in my <title> tags: Error: <title>Invalid URI "../testJSON/user.json"</title> I believe my pathing is correct, so am unsure why it's an invalid URI. I've also provided the entire project...

How to get my node.js mocha test running?

javascript,node.js,mocha,supertest
I have developed a service in node.js and looking to create my first ever mocha test for this in a seperate file test.js, so I can run the test like this: mocha test I could not figure out how to get the reference to my app, routes.js: var _ =...

Meteor: Passing Session values from client to server

javascript,node.js,session,meteor
I am using the following code on the client side to set the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); console.log(clientid + UserSession.get("songsearcher")); I am using the following pacakge: Meteor-User-session, which will explain the use of UserSession in place of Session. Now, this works fine. But...

HTTP query parsed, value read from JSON

javascript,node.js
I get the following JSON from a HTTP query: {"ActuatorNumber":"2","Direction":"right","Speed":"45"} The following code fails to execute: Servo.writeReg((o.ActuatorNumber*2)-1, o.Speed); writeReg comes from the MRAA library. The query is send as following (using curl): "ActuatorNumber=2&Direction=right&Speed=45" It seems like every value of o is read incorrectly. Could there be a parsing error which...

Angularjs Login authentication redirection getting — Error: Can't set headers after they are sent

javascript,angularjs,node.js,express
Very new to NodeJS/AngularJS. I am having problem getting a login page to redirect to another page once the id and password are verified. Codes in the controller are as follows triggered by the route '/login/check': exports.logincheck = function(req, res) { User.findOne({email: req.body.email}).exec(function (err,user) { if (!user) { err =...

Need help understanding the following jQuery code in Socket.io(node.js)?

javascript,jquery,node.js,socket.io
html file <script> var socket = io(); $('form').submit(function(){ socket.emit('chat message', $('#m').val()); $('#m').val(''); return false; }); socket.on('chat message', function(msg){ $('#messages').append($('<li>').text(msg)); }); </script> io.on( "connection", function(socket) { console.log( "A user connected" ); socket.on('disconnect', function(){ console.log('user disconnected'); }); socket.on('chat message', function(msg){ console.log('message: ' + msg); }); socket.on('chat message', function(msg){ io.emit('chat...

What does this line in NodeJs mean?

node.js
I'm wondering what does these require lines in NodeJs mean. var debug = require('debug')('morgan') var deprecate = require('depd')('morgan') I'm going through the index.js of morgan package in NodeJs. Normally require only has one parameter (package). ...

Waiting for promises - code hangs

javascript,node.js,promise
I am using Javascript Promises for the first time and ran into something I don't understand. What I am trying to do is create a validation phase which runs around and checks things - eventually waiting for all promises to resolve. To do this, I create a validation promise: validate...

What type of database is the best for storing array or object like data [on hold]

database,node.js,sockets
I'm just curious what the best method would be if I'm trying to have a bot running on my Node server that I could play Blackjack against. But for multiple connected clients via sockets, each connected socket will have their own bot to play against but I need some way...

How do I run C# within a Node.js server application?

c#,node.js,server
I have a node.js application and a C# algorithm. The algorithm puts out 15 numbers that represent symbols on a digital slot machine. The node server is posting and getting data from Firebase and the digital slot machine is doing the same on the same table. My question is how...

My POST from html does not return any value, nodejs, express

html,node.js,express
I am trying to do a simple post from html page and when I check the console after the post it returns nothing. I have the body parser used correctly on the server side. Is there something that I am doing wrong? var http = require('http'); var fs = require('fs');...

How do i go to parent directory when using __dirname?

javascript,node.js,directory,gulp,gulp-karma
Directory structure : WebApiRole GulpFile.js test Karma.conf.js Gulp code from GulpFile.js gulp.task('test', function (done) { karma.start({ configFile: _configFile: __dirname + '\\..\\test\\karma.conf.js', singleRun: true }, done); }); So my problem going to the parent directory and access the karma.conf.js . For some reason the path is not get resolved with ..\\...

Redis: Delete user token by email ( find Key by Value )

node.js,express,redis
I have followed tutorial on how to create token-based authentication with node from this tutorial http://www.kdelemme.com/2014/08/16/token-based-authentication-with-nodejs-redis/ I got it all worked out, but I got 1 problem. The way I store token is : KEY = TOKEN VALUE = UserData (Username, email, etc.) To protect multiple devices login, I would...

Node.js and C/C++ integration: how to properly implement callbacks?

c++,node.js,multithreading
I am trying to implement a C++ extension to be integrated with node.js. This extension will internally invoke some blocking calls, so it needs to provide a non-blocking interface to the node.js world. As specified in https://nodejs.org/api/addons.html, there are two ways to implement non-blocking callbacks: a) By using a simple...

Calculate a file hash and save the file

node.js,stream
Users upload files into my express app. I need to calc hash of the uploaded file and then write file to disk using calculated hash as a filename. I try to do it using the following code: function storeFileStream(file, next) { createFileHash(file, function(err, hash) { if (err) { return next(err);...

How to add a subdocument in a mongoose schema

javascript,node.js,mongodb,mongoose
I am trying to create a subdocument in a mongoose schema from node.js/Express. I have two schemas: Member and Address Member.js // app/models/member.js // load mongoose since we need it to define a model var mongoose = require('mongoose'), Schema = mongoose.Schema var Address = require('./address'); var MemberSchema = Schema({ FName...

React from NPM cannot be used on the client because 'development' is not defined. The bundle was generated from Webpack

javascript,node.js,npm,reactjs,webpack
I'm creating a React Node.js app and I'm trying to generate a Webpack bundle containing the React source code I loaded from NPM. However, it seems that the React code from NPM cannot be used directly in the client. It triggers this error: Uncaught ReferenceError: development is not defined The...

Getting CROS Error even after adding header in node.js for Angular js

javascript,angularjs,node.js
I am trying to consume REST API from NODE JS for Angular js,even after adding cors header in my server code I am getting error XMLHttpRequest cannot load http://127.0.0.1:8085/issues. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers. I am new to both Angular JS and Node JS. Node JS...

NPM : how to just run post-install?

node.js,npm,package.json
Just a simple question : in my node.js project, how could I just run the postinstall script, without running install before ? FYI, this is my package.json : { "name": "gestionclientjs", ..., "dependencies": { ... }, "repository": {}, "devDependencies": { ... }, "engines": { "node": ">=0.10.0" }, "scripts": { "test":...

How to handle one express route different than all other

javascript,node.js,express,routes
I'm currently using the Express router within a NodeJS application. I have simply been using app.use(app.router); for routing and it works well. However, I'm now testing out some new routes and want to handle them differently. Ideally I would like to be able to say: var vers2Router = require('./routes/version2'); app.use('/version2',...

Secure file upload directly to s3 or server to s3 (from iOS app) [closed]

ios,node.js,amazon-web-services,express,amazon-s3
I need to upload sensitive images to s3 from an iOS app. I'm wondering which option is better: Upload to my server first, then upload to s3. Upload to s3 directly, then upload metadata to my server. ...

I'd like to count the documents with the matching “name” property AND group them by “name” at the same time

node.js,mongoose,group-by
Let's say I have a User collection: schema = mongoose.Schema({ firstName: { type: String, required: true }, ... ... }); module.exports = mongoose.model("User", schema); I would like to write a mongoose query that would count how many users go by the name Mike, Andy, Jerry... In other words, I would...

Create n:m objects using json and sequelize?

javascript,json,node.js,sequelize.js
I am trying to learn sequelize, but am having trouble getting a n:m object created. So far I have my 2 models that create 3 tables (Store, Product, StoreProducts) and the models below: models/Store.js module.exports = (sequelize, DataTypes) => { return Store = sequelize.define('Store', { name: { type: DataTypes.STRING, },...

Socket.IO message doesn't update Angular variable

javascript,angularjs,node.js,sockets
I have a socket.io client-server setup with AngularJS running on the client. // Server.js var io = require('socket.io')(server); io.on('connection', function (socket) { socket.on('message', function (msg) { //console.log(msg); console.log(msg); io.emit('message', msg); }); }); As observed, it essentially emits a message events with the data stored in the variable msg. And then...

NodeJS / ExpressJS check valid token parameter before routing

node.js,express,parameters
I have the following app code: (app.js) var express = require('express') , app = express() , port = process.env.PORT || 8082 app.use(require('./controllers')) app.use(function(req, res, next) { res.send('Test') next() }) app.listen(port, function() { console.log('Listening on port ' + port) }) and two controllers: (index.js) var express = require('express') , router =...

Sails.js sockets. Good and bad sides. Difference with socket.io

javascript,node.js,sockets,socket.io,sails.js
So I am learning Sails.js at the moment and more specifically the integrated socket functionality of the framework. I do like the framework because it is very good for building APIs. My question is can you guys give me some comparison between socket.io and the sails sockets. I mean good...

Memory leak caused by gulp & nodemon

node.js,gulp,mean,nodemon,gulp-livereload
I have this simple gulpfile that basically compiles some less files and triggers livereload. I also have nodemon to restart the server when code is changed. var gulp = require('gulp'), less = require('gulp-less'), autoprefixer = require('gulp-autoprefixer'), minifycss = require('gulp-minify-css'), jshint = require('gulp-jshint'), uglify = require('gulp-uglify'), // imagemin = require('gulp-imagemin'), rename...

Why is address undefined in my app?

node.js,express,jasmine,supertest
I have a simple express app: var express = require('express'); var path = require('path'); var app = express(); exports.app = app; var index = require('./routes/index'); app.use(express.static(path.join(__dirname,'client/dist/'))); app.get('/', index.get); function start(){ var port = process.env.PORT || 8080; app.listen(port, function(){ console.log('app is running on port: ' + port); }); }; exports.start =...

Node.js - Browserify: Error on parsing tar file

javascript,node.js,parsing,tar,browserify
I'm trying to download a tar file (non-compressed) over HTTP and piping it's response to the tar-stream parser for further processing. This works perfect when executed on the terminal without any errors. For the same thing to be utilized on browser, a bundle.js file is generated using browserify and is...

How to use a variable as an Object Key [MongoDB] [duplicate]

node.js,mongodb
This question already has an answer here: How to use a variable as a field name in mongodb-native findOne()? 1 answer I'm trying to use variable name given to me by my function, but its actually setting the object key equal to 'name' function addlist(name, item, id){ // Add...

List running applications using NodeJS

node.js
Using NodeJS I want to get a list of open applications on Windows. Something along the lines of: exec("tasklist", function (error, stdout, stderr) { for(var i=0;i<stdout.length;i++) { if( stdout[i]['name'].indexOf('ll_') > -1 ) { appList.push({'id':stdout[i]['id'],'name':stdout[i]['name']}); } } }); Where appList is an object of running applications with their ID and Name...

Integrating a Single-Page Angular App Template into Sails.js

javascript,angularjs,node.js,sails.js,yeoman
I'm currently trying to build an educational single-page web app which will use Angular for the front end and Sails.js for the backend. I am using an Angular app template which can be found here. I want to integrate it into a Sails.js project, and I even read through and...

Compare Array with Collection-Array containing Objects

node.js,mongodb,mongoose,schema
This is my collection schema: var objectSchema = new Schema({ members: [{ user_id: ObjectId, settings: { type: Boolean } }], title: String }); And now I'm trying to search for objects with specific members (identified by their "user_id", for example ["asdf123lkd", "asdf1223"]). Is there any way to search for these...

Passing data from server/app.js to controller Angular-fullstack + multer

javascript,angularjs,node.js,express,multer
I'm struggling to get a filename passed from server/app.js to a controller in client/app/ I am using Multer to deal with the file upload which is working fine but i need to pass the filename back to the client to display it in the next view. Here is the code...

What happens if all node.js's worker threads are busy

javascript,node.js,multithreading
I try to understand how node.js works and although I have read this article: When is the thread pool used? I am not sure what happens if all worker threads are busy and another async I/O operation is ready to be executed. If I got this http://www.future-processing.pl/blog/on-problems-with-threads-in-node-js/ article right, the...

NGINX Serve all static files and forward others to proxy without / giving 403?

node.js,nginx,proxy
I'm trying to configure an nginx server to act as a proxy to a node application. What I would like is to have any static files served by nginx and all other paths forwarded on to the Node.js application (inluding the / path). I've seen the following question/answers: How to...

What does a [Function] (wrapped in square brackets) mean when inside of a javascript object?

javascript,node.js,javascript-objects
When running console.log on various functions, I'll find properties on the object that have a value of [Function: someFunctionName] in the value section. What does this mean? I want to be able to view the actual code of the function. I'm confused on what's actually being logged when I see...

Mongoose population in instance methods

node.js,mongodb,mongoose,mongoose-populate
I have a model with reference to other documents. I would like to have a method in that model that can process data used in the referenced models. 'use strict'; var mongoose = require('mongoose') , Schema = mongoose.Schema , deepPopulate = require('mongoose-deep-populate'); var MainSchema = new Schema({ childs: [{type:Schema.ObjectId, ref:...

Is there a before() function in Protractor?

angularjs,node.js,automated-tests,protractor,hierarchy
I am aware there is a beforeEach() function which I am currently using. However, I would like to be able to run a before function for all my parent level 'describes' and not the 'it' functions within them. For example my test looks like this (with an x in front...

Check if file exists for ng-include in $routeProvider template

javascript,html,angularjs,node.js,routes
I've setup my Angular routes to use the slug from the URL to determine what file to load. It looks like this: $routeProvider.when("/project/:slug", { controller: "ProjectController", template: function($routeParams){ return '<div id="project" ng-include="\'/views/' + $routeParams.slug + '.html\'"></div>'; } }); Works a charm, but there's no fallback here if the file for...

Send code via post message is not working

javascript,node.js,express,postman
I wanted to send code to some node application and I use the postman with post message and in the body I put the following: module.exports = function() { var express = require('express'), app = express(); app.set('port', process.env.PORT || 3000); return app; } in the header of the request I...

Node Server - Source Code accessible

node.js,express
I noticed that when i navigate to localhost:8080/server.js (where my server.js is the server-expressjs obviously) the code of my server is shown in the browser! Even, if i upload the application to openshift, i get the same result (you can test it): http://tickets-shkobba125.rhcloud.com/ http://tickets-shkobba125.rhcloud.com/server.js Is this a security issue? How...

Sails.js multiple databases in multiple environments

node.js,sails.js
I have been going round in circles trying to get this to work how I think it should in sails v 0.11.0 I have my development.js as follows module.exports = { connections: { conn1: { adapter: 'sails-sqlserver', user: 'user', password: 'pass', server: 'server1', database: 'db1', options: { encrypt: true }...

video to audio file convert & save through FFMPEG in node js

javascript,node.js,audio,video,ffmpeg
I am working on an FFMPEG on node js. I'd like to retrieve the audio track from a video file using node js. I would also like to save such file but I can't figure out how. I though this line of code would help me : ffmpeg('/path/to/file.avi').noVideo(); I have...

Regex for one, two, three etc using Node.js

regex,node.js
I am working on regex and facing one problem. I am not able to finding one, two, three, four etc. in string using regex in node.js. Example: String contains some time Chapter 1 or Chapter one. I can find 1 but not one. Chapter one Chapter two Chapter three Chapter...

Is there a built-in function to get all unique values in an array field, across all records?

arrays,node.js,mongodb,mongoose,schema
My schema looks like this: var ArticleSchema = new Schema({ ... category: [{ type: String, default: ['general'] }], ... }); I want to parse through all records and find all unique values for this field across all records. This will be sent to the front-end via being called by service...

How to handle expressjs middleware request. post request remains pending made by dropzone

node.js,express,dropzone.js,multer
I am using dropzone to upload the file. On the server side I am using node and expressjs. I am also using multer as the file handling middleware. dropzone makes a call to one endpoint to save the file on the server. On the server side, I created an endpoint...

websockets - reject a socket connection

node.js,sockets,websocket
I'm using ws as the socket library for my node.js library. so my question is, how can I reject a connection if the user doesn't pass the authorization process. var WebSocketServer = require('ws').Server; var wss = new WebSocketServer({port: 6969}); wss.on('connection', function(socket){ // if the socket.upgradeReq.headers.cookie doesn't exists, reject the client...

How to use promises to do series without duplicate code

node.js,promise,bluebird
I need execute a code in series, I need execute the same function N times Example // execute asynFunc 4 times in series object.asynFunc() .then(function() { return object.asynFunc(); }) .then(function() { return object.asynFunc(); }) .then(function() { return object.asynFunc(); }) I want execute the same function 100 times...

Is 'console.time' in nodejs synchronous or async?

javascript,node.js,console
I am trying to log time for something. The general code looks like so: var stream = db.call.stream(); stream.on('data', function () { if (first) { console.time('doSomething'); } stream.pause(); doSomethingWithData(data); if (stopCondition) { console.timeEnd('doSomething'); done(); } else { stream.resume(); } }); I would like to know if the call to console.time...

jQuery DataTables with Node.js

javascript,jquery,node.js,datatables,jquery-datatables
So i am trying to implement a pagination table with the datatables plugin, this is my first time using this plugin. I followed the documentation on the plugin and tried to get the values from the server through the use of Ajax, as per presented in the plugins documentation. I...

Emitting and receiving socket io within the same file

node.js,express,socket.io
I want to do something where I can set up a route to a link like /visit using app.get('/visit', function(req, res){}) etc. And inside that, I want to emit a message like socket.emit("event", "a message") and then inside my io.on("connection") function, be able to listen for event and return the...

After deploying to heroky scripts and css not available

node.js,heroku
I am new in heroku. Locally project works fine but after deploying vendor scripts files are not available. Their paths are redirected to main page. Here is the deployed version with errors https://salty-woodland-8424.herokuapp.com/. In nodeJs file i use var express = require('express'); var path = require('path'); var stylus = require('stylus');...

Error is not thrown inside a deferred method

node.js,exception-handling,deferred
Can somebody explain to me why my error is not thrown in my first example? And why it is when I use process.nextTick() ? var deferred = require('deferred'); // This code does not work. // Error seems to never been thrown and script kind of freeze without saying anything. deferred.resolve().then(function(){...

Express 4 register handlebars

javascript,node.js,handlebars.js
I'm trying to run the Handlebars example with Node.js. However, I'm having trouble registering Handlebars. I keep on getting the error Error: callback function required at line 7. var express = require('express'); var app = express(); var port = process.env.PORT || 8888; var router = express.Router(); app.set('view engine', 'html'); app.engine('html',...

How do I send stdout in real time from nodejs to angularjs?

javascript,python,angularjs,node.js
I have a script that runs for a long time. It generates an output. I am running this script from nodejs using child_process. How do I send the output of this script soon as it starts executing and do not wait for the script to complete. The code that I...

With Sails.js how can I make /users/me a route that works with associations?

javascript,node.js,sails.js
Hi guys I have a main model Accounts, then I have a few Has Many models like Notifications and Friends In my main.js I'd like to be able to do things like: socket.get('/users/me/notifications'); instead of like: socket.get('/users/ + g_userAccountId + '/notifications'); ^^ That works for right now, but it is...

mongodb populate method not working

node.js,mongodb,model,populate,auto-populate
Here is my code for models var postSchema = new mongoose.Schema({ created_by: {type: Schema.ObjectId, ref:'User', autopopulate: true }, //should be changed to ObjectId, ref "User" created_at: {type: Date, default: Date.now}, text: String }); var userSchema = new mongoose.Schema({ username: String, password: String, //hash created from password created_at: {type: Date, default:...

Add multiple rows from same model AngularJS

angularjs,node.js
Considering I have a list of users to add into my system and I don't want to do it one-by-one process. Then I want to see one user form (name, email, password fields) and by the end of the row i see the "add another row" button. By clicking on...

Rethinkdb with nodejs and expresso

node.js,rethinkdb,expresso
I am trying to use rethinkdb and test it via expresso. I have function module.exports.setup = function() { var deferred = Q.defer(); r.connect({host: dbConfig.host, port: dbConfig.port }, function (err, connection) { if (err) return deferred.reject(err); else deferred.resolve(); }); return deferred.promise; }); I am testing it like this module.exports = {...

Using middleware to call an Authentication API using ExpressJS

angularjs,node.js,authentication,express
I'm using two Node.js + Express applications: Backend Authentication And my front-end is built in AngularJS Basically I'm trying to send a json web token with every request to the Backend, and then use a route middleware to call the Authentication API. It validates that token and add user data...

Sockets make no sense?

javascript,node.js,sockets
I'm using the 'ws' library for Node.js. I can write code that sends data from my server to my client, posting a date and time update, and closes the socket when I click a button; var wss = new WebSocketServer({server: server}); console.log("WebSocket server created"); wss.on('connection', function(socket) { // SEND DATE...

Refactoring Express Routing

node.js,express
I have many express routes doing similar functionality, with the exception of the .put which handles specific functionality. What would be the best way to refactor this type of code. Require Statements var Ale = require('../models/alert-model.js'); var Service = require('../models/services-model.js'); Routes router.route('/ale/:_id') .get(function(req, res) { Ale.findById(req.params._id, function(err, result) { if...

what is the nodejs package for s3 image upload

node.js,image,amazon-s3
I'm looking to upload my assets to s3. Is there any package in Nodejs like carrierwave in rails I want to resize images with versions. I have come across papercut. What is the best node module for s3 image upload....

How to get node.js to connect to mongolab using mongoose

database,node.js,mongodb,mongoose,mongolab
I've been trying to use mongoose (module for node.js and mongodb). And tried to get a connection with mongolab up and running. I tried the following at the top of my app.js file, but I couldn't seem to enter the db.on function. global.mongoose = require('mongoose'); var uri = 'mongodb://username:password#####@ds.mongolab.com:#####/db'; global.db...

Having trouble looping through DOM elements with node web scraper

javascript,jquery,node.js
I was able to get the scraper to do what I want it to do, I'm having a lot of issues actually getting it to loop through the pages I want it to loop through. I think my issue may be with the placement of my for loop and how...

hasMany relation: including from the other direction

node.js,strongloop,loopback
Say I have the next model: user.json: {//... "relations":{ "invoices": { "type": "hasMany", "model": "Invoice", "foreignKey": "receiverId" }, } //... } A.k.a. a user might have many invoices. This code adds the field receiverId to the invoice model. Now I want to get a list of invoices including their receivers....

Express get error

node.js,model-view-controller,express
I am setting up routes to my application controller on a node server - var http = require('http'); var app = require('express')(); app.get('/<path>/<query type>', function(req, res) { //Expecting query parameter <query type>?name=<something> var query = req.query.name; var path = '/<path>/<query type>?name='+query; var options = { host: 'localhost', port: 8080, path:...

node ssh2 shell unable to run apt-get install on remote machine

node.js
I'm doing a program in node.js to deploy my code from git to a server (Digital Ocean). I'm connecting to the server via ssh2 module and running commands via shell, like bellow: var Client = require('ssh2').Client; var conn = new Client(); conn.on('ready', function() { console.log('Client :: ready'); conn.shell(function(err, stream) {...

What are some patterns I can look at for database implementations in JavaScript?

javascript,node.js,mongodb
I'm fairly new to JavaScript, and I'm busy playing around with a node test app and MongoDB. I'm at a point where I'd like to start with the db side of the app, but I'm not sure what patterns are most commonly used in such a stack, and more importantly,...

NodeJS for a JAVA developer - Few Questions

java,node.js,express
I'm working on a project that is heavily based on json. Since 90% of the server side in JAVA would be POJO.toJSON() I decided to give NodeJS a shot! Most of my questions are related to the fact that NodeJS runs as a single thread. Am I right? :) NodeJS...

Getting failed to load c++ bson extension error using Mongodb and Node.js

javascript,node.js,mongodb
I am getting the following error while trying to run server using Node.ja with Mongodb. Error: { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++...

Mongoose : update collection with previous data

node.js,mongodb,mongoose
I am learning NodeJs and for a demo project i need to use MonGoDB with Mongoose. I created a collection for a photo album. The first row is : albumName and the second row is : pictures. I don't undersand how i can save all my pictures in the row...

What is wrong with Nodejs?

node.js,express,runtime-error,middleware,multer
I am using multer to handle upload image. app.use(multer({ dest: './public/photos', rename: function (fieldname, filename) { return filename+Date.now(); }, onFileUploadStart: function (file) { console.log(file.originalname + ' is starting ...') }, onFileUploadComplete: function (file) { console.log(file.fieldname + ' uploaded to ' + file.path) //a='asass'; done=true; } })); app.post('/api/photo',function(req,res){ if(done==true){ //ERROR here...

How to add new items to an array in MongoDB

arrays,node.js,mongodb
I'm trying to add a new item to whichever name that was passed in under whichever id. My first problem is that it seems like its not grabbing the values from any of my variables (name, item, id), instead just using them as object keys. My next issue is that...