Saturday 3 June 2017

Updating a mongoose collection after doing insertMany() in nodejs

I have some JSON dumps with over a thousand records in a JSON array format. These dumps would be created nightly and my job is to keep my db synced with these dumps. Initially for testing I did model.insertMany(json) as I read that it is much more efficient than doing multiple calls to the db. But naturally I cannot use this for my nightly updates since insertMany() fails when a key exists. What should I do in its place which is as efficient?



via Sayak Mukhopadhyay

WSL - Cannot install gulp locally in /var/www

I am running an apache2 web application on Bash on Windows - WSL. The project has following node dependencies described in package.json

{
    "name": "xxx",
    "version": "1.0.0",
    "private": true,
    "dependencies": {
    },
    "devDependencies": {
    "gulp": "^3.9.1",
    "gulp-uglify": "^1.5.1",
      "gulp-concat": "^2.6.0",
      "gulp-sourcemaps": "^2.4.0"
    },
  "engines": {
    "node": ">=4"
  }
}

Doing a simple npm install gives errors similar to the one below. So, I used sudo npm install -g on all the packages manually. Since gulp still needs a local copy in the project directory, it needs npm install gulp --save-dev commands. This generated following error.

user@DESKTOP:/var/www/xxx/xxx$ sudo npm install gulp --save-dev
npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
npm ERR! path /var/www/xxx/xxx/node_modules/gulp

npm ERR! code ENOENT
npm ERR! errno -2
npm ERR! syscall rename
npm ERR! enoent ENOENT: no such file or directory, rename '/var/www/xxx/xxx/node_modules/gulp' -> '/var/www/xxx/xxx/node_modules/.gulp.DELETE'

npm ERR! enoent This is related to npm not being able to find a file.

npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/user/.npm/_logs/2017-06-04T06_06_31_779Z-debug.log

Also, by default all files and directories in /var/www in WSL have root:root user:group. Local node_modules/ directory is always empty.



via stWrong

npm global package installing issue

I have faced an issue when I have tried to install Vue CLI.

windows 10, node ~ 6.10.3 npm ~ 3.10.10

npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'D:\Users\Subho\AppD                                                                            ata\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chromium-1.3.13.tgz.111430805                                                                            1' -> 'D:\Users\Subho\AppData\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chr                                                                            omium-1.3.13.tgz'
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "D:\\Program Files\\nodejs\\node.exe" "D:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js"                                                                             "install" "--global" "vue-cli"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10

npm ERR! tarball.destroy is not a function
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>
npm WARN retry will retry, error on last attempt: Error: EBUSY: resource busy or locked, rename 'D:\Users\Subho\AppD                                                                            ata\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chromium-1.3.13.tgz.311380074                                                                            4' -> 'D:\Users\Subho\AppData\Local\Temp\npm-9484-8858437e\registry.npmjs.org\electron-to-chromium\-\electron-to-chr                                                                            omium-1.3.13.tgz'
npm ERR! Windows_NT 10.0.14393
npm ERR! argv "D:\\Program Files\\nodejs\\node.exe" "D:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js"                                                                             "install" "--global" "vue-cli"
npm ERR! node v6.10.3
npm ERR! npm  v3.10.10

npm ERR! tarball.destroy is not a function
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

Please help me how I fixed the issues and install the vue cli



via Subhojit Mondal

how to read terminal input by node javascript?

I want to do some local node test before push the code to server.

how can I read terminal input as a input for my js script? readline or something

thanks!



via Dark Lei

Are type definitions for npm packages required only on developer machine?

As I understand, the type definition modules (for npm packages) provide intellisense for developers so that they don't have to guess parameter types when calling library methods. For example, these modules are very useful in my typescript project when I consume third party libraries (along with their type definition modules) in my vscode editor.

  1. Is this the only purpose (i.e. provide intellisense) in for type definition modules?
  2. If the answer is yes, then they should not be required on build servers and production machines. Is this true?


via Raghu

Upserting with Mongoose

I have a schema that is defined like

var UserSchema = mongoose.Schema({
    user: {
        ipAddress: String,
        pollIDs: [{
            id: String
        }]
    }
});

var User = module.exports = mongoose.model('User', UserSchema);

What I want to create is a route that checks the requests ip address, see if it exists in the database, if it doesn't create a new document with the ipAddress property set accordingly and the current req.body.poll_id to be an element in the pollIDs array.

However, if there is a document with that ip address I want the req.body.poll_id to be pushed into the pollIDs array.

I would demonstrate my first attempt, but I know that I've messed up the parameters on the findOneAndUpdate call.



via daman

Nodejs + Golang OR PHP + Golang in Three Tier Web Application

I want to build fast and robust web application that can handle a lot request per second. Actually the confusion is choosing between Nodejs and PHP as Application Layer. where PHP is mature and it has various framework option and Nodejs is super fast and has amazing feature like socket + ease at DOM manipulation since it's basically javascript + bright future(This idea comes after some RnD).

Which is the best between PHP and Nodejs to achieve the goal?



via Angger

electron browser javascript error

I am very new to node, javascript, and electron. I am just trying to write a simple app that opens a local HTML file in a browser window. The local file has some complex embedded javascript (tiddlywiki). Here is some sample code (I did not use local file in this one, but the result is the same):

const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

let win

function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})


// and load the index.html of the app.
win.loadURL(url.format({
    pathname: 'tiddlywiki.com',
    protocol: 'http:',
    slashes: true,
    webPreferences: {
      nodeIntegration: false,
 }
 }))

When the electron app launches I get the following error in the browser dev tools.

Uncaught TypeError: Cannot read property 'length' of undefined
    at Object.$tw.boot.startup (tiddlywiki.com/:27506)
    at tiddlywiki.com/:27765
    at Object.$tw.boot.decryptEncryptedTiddlers (tiddlywiki.com/:27053)
    at Object.$tw.boot.boot (tiddlywiki.com/:27763)
    at _boot (tiddlywiki.com/:27772)
    at tiddlywiki.com/:27782

I assume this is because of some integration of the node.js object model? Sorry for the lack of understanding. Thanks in advance for the help.



via BrandonKurtz

Nodejs - Global or local initialisation of libraries

I am a bit confused as to which of the below is the better practice and why? In the first, we initialise the library globally and in the second case, its done inside a function.

Code 1

var twilio_client = require('twilio')(
  process.env.TWILIO_ACCOUNT_SID,
  process.env.TWILIO_AUTH_TOKEN
);

function_sendSMS(from, to){
   twilio_client.messages.create({
     from: from,
     to: to,
     body: "You just sent an SMS from Node.js using Twilio!"
     }, function(err, message) {
     if(err) {
      console.error(err.message);
     }
  });
}

Code 2

function_sendSMS(from, to){

   var twilio_client = require('twilio')(
     process.env.TWILIO_ACCOUNT_SID,
     process.env.TWILIO_AUTH_TOKEN
   );

   twilio_client.messages.create({
     from: from,
     to: to,
     body: "You just sent an SMS from Node.js using Twilio!"
     }, function(err, message) {
     if(err) {
      console.error(err.message);
     }
  });
}



via npm install mad-monkey

How to auto-initiate ESLint in Atom using modified rules?

I'm just getting into Atom and ESLint - heck still a noob using Node and npm.

I've got a project working fine with Atom, Linter and ESLint, and I customized the rules of the "standard" config (as opposed to Google or AirBnB).

When I start a new project, however, nothing is carried over. It looks like I have to re-init ESLint, and then it asks for the config file again, which is obviously not my customized version.

How can I get ESLint to run automatically whenever Atom opens a JS file, using my custom rules?

Thanks in advance and let me know if my terminology is off...



via calipoop

Can't print result of a function

I am trying to use the Watson Translator API to translate a user given input "input", and store it in a global variable "res" for later use in the Watson Conversation service, but I find myself unable to print or verify if the value was truly affected to my variable "res", here is my code :

var res;

function Translate(input, res){

 language_translator.translate({
    text: input,
    source: 'en',
    target: 'fr'
 }, function(err, data) {
    if (err)
        console.log(err)
    else {
        console.log('within translate function data is : '+ data.translations[0].translation);
        show(data.translations[0].translation);
    }
 });


 let show = function(data){
    console.log('within show function data is : '+ data);
    res = data;
    console.log('res inside show function : '+res);
 }

}

Translate('hello', function(){
  print();
});


function print(){
  console.log('final : '+res);
}

Result prints as follows :

within translate function data is : Bonjour
within show function data is : Bonjour
res inside show function : Bonjour



via Joe25

getting 2 docs by score and breaking the tie

How would I go about displaying the best reviews and the worst reviews at the top of the page.

I think the user's "useful" and "notUseful" votes should have an effect on the result.

I have reviews and if people click on the useful and notUseful buttons their Id gets added to the appropriate array (useful or notUseful).

you can tell what a positive or a negative score is by the "overall" score. that is 1 through 5. so 1 would be the worst and 5 would be the best.

I guess If someone gave a review with a 5 overall score but only got one useful but someone gave a score with a 4 overall and 100 people clicking on "useful" the one with 100 people should be shown as the best positive?

I only want to show 2 reviews at the top of the page the best and the worst worst review if there are ties with the overall scores the deciding factor should be the usefulness. so if there are 2 reviews with the same overall score and one of them has 5 usefuls and 10 notUsefuls that would be -5 usefuls and in the other review someone has 5 usefuls and and 4 notUsefuls that would be 1 usefuls so that would be shown to break the tie.

I'm hopping to do it with one mongoose query and not aggregation but I think the answer will be aggregation.

I guess there could be a cut off like scores greater than 3 is a positive review and lower is negative review.

I use mongoose. Thanks in advance for your help.

some sample data.

{
    "_id" : ObjectId("5929f89a54aa92274c4e4677"),
    "compId" : ObjectId("58d94c441eb9e52454932db6"),
    "anonId" : ObjectId("5929f88154aa92274c4e4675"),
    "overall" : 3,
    "titleReview" : "53",
    "reviewText" : "53",
    "companyName" : "store1",
    "replies" : [],
    "version" : 2,
    "notUseful" : [ObjectId("58d94c441eb9e52454932db6")],
    "useful" : [],
    "dateCreated" : ISODate("2017-05-27T22:07:22.207Z"),
    "images" : [],
    "__v" : 0
}


{
    "_id" : ObjectId("5929f8dfa1435135fc5e904b"),
    "compId" : ObjectId("58d94c441eb9e52454932db6"),
    "anonId" : ObjectId("5929f8bab0bc8834f41e9cf8"),
    "overall" : 3,
    "titleReview" : "54",
    "reviewText" : "54",
    "companyName" : "store1",
    "replies" : [],
    "version" : 1,
    "notUseful" : [ObjectId("5929f83bf371672714bb8d44"), ObjectId("5929f853f371672714bb8d46")],
    "useful" : [],
    "dateCreated" : ISODate("2017-05-27T22:08:31.516Z"),
    "images" : [],

    "__v" : 0
}


{
    "_id" : ObjectId("5929f956a692e82398aaa2f2"),
    "compId" : ObjectId("58d94c441eb9e52454932db6"),
    "anonId" : ObjectId("5929f93da692e82398aaa2f0"),
    "overall" : 3,
    "titleReview" : "56",
    "reviewText" : "56",
    "companyName" : "store1",
    "replies" : [],
    "version" : 1,
    "notUseful" : [],
    "useful" : [],
    "dateCreated" : ISODate("2017-05-27T22:10:30.608Z"),
    "images" : [],
    "__v" : 0
}



via jack blank

Running an passed function and passport.authenticate

hope your day is going well. I want both the function that sets the JWT and the passport.authenticate to run but only the former is running. Is there a way I can have both run?

   router.post('/login',(req, res, next) => {

        console.log(req.body.username);
        const userEmail = req.body.username;

        User.getUserByEmail(userEmail, function(err, user){


            const token = jwt.sign(user, config.secret, {
                             expiresIn: 604800 // 1 week
                         });
            new Cookies(req,res).set('access_tokenx',token,{
                httpOnly: true,
                secure: false      
            });
            return res.send();

        });
    },
      passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
      function(req, res) {
        res.redirect('/');
      });

Thanks in advance, Ed.



via Ed Lynch

Is it a smart idea to use setInterval to update a time frequently?

How much of an impact on the server would there be if I used a setInterval like this to continue changing the time displayed in the browser every 10 seconds for example:

setInterval(function(){
  var time = moment($('#bidTime').val());
  $('#ago').text(time.fromNow());
  $('#ago2').text(time.fromNow());
}, 10000);

On the dashboard of my web app, I have a "Last Updated" column with a displayed time that I want to display "xx seconds ago" etc..

Is it bad to use setInterval in this case? Is there a better way?



via kolbykskk

Server Listening but not able to Connect Node

So I am trying to get started on a Node App. Right now I am just setting up my server. I am using Node, Express, Handlebars, and MongoDB. So, I have set up my server and it seems to be working fine. It is listening on Port 8080. But when I go to localhost://8080, I am getting an error message: "Localhost refused to connect."

I have tried to change my routing, etc and have had no luck fixing it. I am guessing that it is my router, or maybe how I am trying to render the page. You can see my server.js and routing file here:

var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose"); 
var methodOverride = require("method-override");



// Our scraping tools
var request = require("request");
var cheerio = require("cheerio");

// Set mongoose to leverage built in JavaScript ES6 Promises
mongoose.Promise = Promise;

// Initialize Express
var app = express();
var port = process.env.PORT || 8080;
// Use morgan and body parser with our app
// Override with POST having ?_method=DELETE
app.use(methodOverride("_method"));
app.use(bodyParser.urlencoded({
extended: false
}));

// Make public a static dir
app.use(express.static("public"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.text());
app.use(bodyParser.json({ type: "application/vnd.api+json" }));
// Database configuration with mongoose
mongoose.connect("mongodb://localhost/week18day3mongoose");
var db = mongoose.connection;
// Show any mongoose errors

db.on("error", function(error) {
  console.log("Mongoose Error: ", error);
});

// Once logged in to the db through mongoose, log a success message
db.once("open", function() {
  console.log("Mongoose connection successful.");
});

// Set Handlebars.
var exphbs = require("express-handlebars");
app.engine("handlebars", exphbs({ defaultLayout: "main" }));
app.set("view engine", "handlebars");



app.listen(function(){
 console.log("Server is running and lisening on port: " + port);
});


require("./routes/htmlRoutes.js");

Here is my router:

var express = require("express");


module.exports = function(app) {

   router.get("/", function(error,doc){
     res.send("Hello World");
 });

}

You can see the entire project up to this point here: https://github.com/Bentley912/Article-Scraper



via Patrick Bentley

what happend if i don'nt use 'haltOnTimedout' in express middleware 'connect-timeout'?

I'm new to express, I don'nt understand this connect-timeout middleware. Please visit this website: https://github.com/expressjs/timeout When using this as top-level,why I must use 'haltOnTimedout'? What happend if I donn't use it? I have already tried the below:

app.get('/', function(req, res, next) {
    console.log('/')
})

But I still puzzled. Who can explain me, thanks in advance!



via vcxiaohan

How to deploy to Heroku the right way?

I am trying to deploy an app to Heroku with Github. But for some reason I am getting an error in my log, that I think its referring to my Procfile. So, when I have created repo in github, to I have created a index.js that is the web server were I want Heroku to start with.. So, can anyone help me to deploy to heroku with Github. Thanks in advance.

Here is my code:

Procfile:

 web: node index.js

Index.js:

var express = require('express');
var app = express();
var path = require('path');
var http = require('http').Server(app);
var io = require('socket.io')(http);

var routes = require('./routes');
var chats = require('./chat');



app.use(express.static(path.join(__dirname, '../public')));

routes.load(app);
chats.load(io);


// app.listen(process.env.PORT || 5000, function () {
//     console.log('Express server listening....', process.env.PORT);
// });


http.listen(3000, function () {
  console.log('listening on *:3000');
}); 



via Billy Jr.

Security Mongo Database in Azure Virtual Machine

I've a Node Web App with Mongo DB running in Azure Virtual Machine. The connection string is similar to user:pass@IP:27017/MyDatabase

Nowdays Mongo database was stolen by "request@firemail.cc" email with the next message: "Your DB is in safety and backed up (check logs). To restore send 0.1 BTC and email with your server ip or domain name. Each 24 hours we erase all data.

I've credentials as Environment Variable in Azure and I don't have code source in a public repository.

Any suggestions to make Mongo Database safer or other advices in Azure to be considered?

Thanks a Lot.



via Gianfranco Manrique Valentín

Cannot connect to node.js/express.js server. (ERR_EMPTY_RESPONSE)

I cannot connect to my local node.js/express server. I get the error ERR_EMPTY_RESPONSE after ~2 minutes of loading. I'm running the server on the same machine that i am trying to connect from.

Here's my code:

const express = require('express');
const fs = require('fs');
const cookieParser = require('cookie-parser');
const pug = require('pug');

const config = require('./helpers/config.js');
const app = express();

app.engine('pug', require('pug').__express);
app.set('views', './views')
app.set('view engine', 'pug');

app.use(express.static(__dirname + '/public'));
app.use(require('./middlewares/auth'));

app.use(function (req, res, next) {
  console.log("Error!");
  res.status(404);

  if (req.accepts('html')) {
    res.render("404", {url: req.url})
    res.end()
    return
  }else if (req.accepts('json')) {
    res.send({error: 404, message: "Not found!"})
    res.end()
    return
  }

  res.type('txt').send('404 Not found!')
  res.end()
})

app.get('/', function (req, res) {
  console.log("root");
  res.render('index', {message: "Hello World!"})
  res.end()
})

app.listen(3000, function() {
  console.log('Listening on port 3000...');
})



via Theo Sandell

Defer Node.js HTTP requests if similar work already being done

I'm making a service which retrieves a photograph from a remote host and does some processing before passing it on to the client. It caches the retrieved source photo locally to avoid retrieving it again later on.

However, if there are several requests in rapid succession, the source image will not yet have been saved locally, and unnecessary retrievals are performed.

What is a nice approach to defer the incoming requests until the source image is cached, provided it's already currently being retrieved?

I'm currently using Node.js streams all the way from the inbound request stream, passing it through my caching and transformation logic, passing it to the outbound stream.



via sune

Angular.io (probably node.js) way to create/import javascript files as modules

I would like first of all to point out that my knowledge in this field is pretty limited at this moment and the purpose of this question is to start moving the direction where the things become clear and useful.

For the purpose of this question, the following Typist plugin has been selected, where the author suggests to import the code using the good old <script> tag inside the index.html. But for example in angular/react and other component based frameworks it has become very common to import modules into a component and directly implement them inside.

Can you please define/suggest a route of basic logic/information I should learn in order to be able consciously declare and manage such plugins as modules, import them into components and launch directly from the last ones.



via Adrian Sol

install error npm takana on ubuntu

I am trying to install takana using npm. It work on mac but did not work on ubuntu 17.04. I update nodejs-v v8.0.0 and npm-v =>5.0.2 but it display below

Fatal error in ../deps/v8/src/api.cc, line 1197 Check failed: !value_obj->IsJSReceiver() || value_obj->IsTemplateInfo().



via zouhair

Can i build a Node js authencation system without passport js

i searched for a tutorial to make Node js authencation system without passport js but all tutorials i found were using passport js

so, can i do it without passport ?



via Mr Leo

Mongoose store either ObjectId reference or string

Is there a way to specify a heterogeneous array as a schema property where it can contain both ObjectIds and strings? I'd like to have something like the following:

var GameSchema = new mongoose.schema({
    players: {
        type: [<UserModel reference|IP address/socket ID/what have you>]
    }

Is the only option a Mixed type that I manage myself? I've run across discriminators, which look somewhat promising, but it looks like it only works for subdocuments and not references to other schemas. Of course, I could just have a UserModel reference and create a UserModel that just stores the IP address or whatever I'm using to identify them, but that seems like it could quickly get hugely out of control in terms of space (having a model for every IP I come across sounds bad).



via Turner Hayes

Why is the API response time for Audio Stream Recognition so slow?

I am using very similar code to Google's example for performing speech recognition on an Audio stream using the Node.js client library.

The API is parsing my audio correctly, but I find myself waiting 30-45 seconds before I get a response. Considering how snappy the demo is, this doesn't seem right. Is there something I am configuring incorrectly on my end?

I've tried writing to a local file instead just to make sure the audio is coming through clearly, and the recording seems fine.

Thanks for any help you can give!

import record from 'node-record-lpcm16';
import Speech from '@google-cloud/speech';


function streamToParser(){
  const speech = Speech();
  const request = {
    config: {
      encoding: 'LINEAR16',
      sampleRateHertz: 16000,
      languageCode: 'en-US',
    },
    interimResults: true,
  };

  const recognizeStream = speech.createRecognizeStream(request)
  .on('error', console.error)
  .on('data', (data) => {
    console.log(data.results)
  });

  record
  .start({
    sampleRate: 16000,
    threshold: .6,
    verbose: true,
    silence: '5.0'
  })
  .on('error', console.error)
  .pipe(recognizeStream)

  console.log('Google is listening...')
};



streamToParser();



via JWayne

NodeJs No 'Access-Control-Allow-Origin' header is present on the requested resource

I am trying to access an rss feed using an Ajax request on the client broswer.

$.ajax({
type: 'GET',
url: 'http://feeds.bbci.co.uk/news/business/rss.xml?edition=uk',
crossDomain: true,
dataType: 'xml',
success: function(responseData, textStatus, jqXHR) {
    console.log(responseData)
},
error: function (responseData, textStatus, errorThrown) {
    alert('failed.');
}
});

This is giving me the 'Access-Control-Allow-Origin' error.

I have installed the cors package so it should be enabled on my server, am i missing something?

server.js file

var express = require('express');
var basicAuth = require('express-basic-auth')
var bodyParser = require('body-parser')
var cors = require('cors');
var app = express();

app.use(cors()); 

app.get('/', function (req, res) {
//    res.send('Hello World');
    res.sendFile(__dirname + '/views/index.html');
})

var routes = require('./routes');
app.use('/api', routes);


var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("App listening at http://%s:%s", host, port)
})



via user2202098

Sequelize has and belongs to many

Is there a way to do a polymorphic self-association with a through table (e.g. Collection has and belongs to many Collections)?

Trying to adapt http://docs.sequelizejs.com/manual/tutorial/associations.html#n-m to this scenario:

// Inside collection.js associate
Collection.belongsToMany(Collection, {
    through: {
        model: models.CollectionItem,
        unique: false,
        scope: {
            collectible: 'collection'
        }
    },
    foreignKey: 'collectibleUid',
    constraints: false
});

Where collectionItem.js would look like

const CollectionItem = sequelize.define("CollectionItem", {
    uid: {
        type: DataTypes.BIGINT,
        primaryKey: true
    },
    collectionUid: {
        type: DataTypes.BIGINT,
        allowNull: false,
        unique: 'collection_item_collectible'
    },
    order: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0
    },
    collectibleUid: {
        type: DataTypes.BIGINT,
        allowNull: false,
        references: null, // Because the column is polymorphic, we cannot say that it REFERENCES a specific table
        unique: 'collection_item_collectible'
    },
    collectible: {
        type: DataTypes.STRING,
        allowNull: false,
        unique: 'collection_item_collectible'
    }
}, {
    classMethods: {
    }
});

It seems Sequelize wants me to name this differently through yet another join / through table: Error: 'as' must be defined for many-to-many self-associations



via iwasrobbed

Node Js session does not persist only when I use post request

Hi all im having problem getting session variables when i use 'POST' as request method.

My code as follows:

index.js:

var express = require("express");
var app = express();
var path = require('path');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var pagesRouter = require('./routes/router');
var cookieParser = require('cookie-parser');
var cookieSession = require('cookie-session');
var sessions = require('client-sessions');
var cors = require('cors');

app.use( express.static( __dirname + '/static' ));
app.use(cookieParser('a secret'));
app.use(cookieSession({
  secret: 'a secret',
  resave: false,
  saveUninitialized: true,
  cookie: { path: '/', httpOnly: true, maxAge: 30 * 60 * 60 * 1000 },
  rolling: true}));
app.get('/selam', function(req,res){
  res.send(req.session.test);
});

app.use(bodyParser.urlencoded({
  extended: true
}));

app.use(bodyParser.json());

app.use(pagesRouter);

app.listen(8080,function(){
  console.log("Live at Port 8080");
});

router.js

var express = require("express");
var router = express.Router();
var path = require('path');
var request = require('request');
var session = require('client-sessions');
var apiPath = "http://localhost:8070/api/";
var webPath = "http://localhost:8080";

router.get("/",function(req,res){
  res.sendFile(path.join(__dirname,'../static/views/index.html') );
});

router.post("/login", function(req,res){
  request.post(
      apiPath + "auth",
      { json: { email: req.body.email, password: req.body.password } },
      function (error, response, body) {
          if (!error && body.statusCode == 200) {
            req.session.userId = body.userId;
            req.session.token = body.token;
            req.session.save();
            console.log("session user: " + req.session.userId);
            res.send(body);
          }else{
            res.writeHead(301,
              {Location: webPath+"?loginError=true"}
            );
            res.end();
          }
      }
  );
});


router.get('/test', function(req,res){
  req.session.test1 = "hi all";
  res.end();
});

router.get('/test1', function(req,res){
  res.send(req.session.test1);
});
/*router.use(function (req,res,next) {
  console.log(req.session.userId);
  if(!req.session.userId){
    res.writeHead(302, {'Location': webPath + '/'});
    res.end();
  }
  else
    next();
});*/

module.exports = router;

index.html (part that posts login request)

      <div class="col-xs-12 col-sm-6">
        <h3 class="text-center">SIGN IN</h3>
        <br>
        <form class="form-horizontal" method="post" action="/login">
          <div class="form-group">
            <div class="col-lg-12">
              <input type="text" class="form-control" id="login-email" placeholder="Email" name="email">
            </div>
          </div>
          <div class="form-group">
            <div class="col-lg-12">
              <input type="password" class="form-control" id="login-password" placeholder="Password" name="password">
            </div>
          </div>
          <div class="text-right">
            <button type="submit" class="btn btn-default">sign in</button>
          </div>
        </form>
      </div>

the problem is that when I use post in that form and post it directly with form's submit button userId and token is not written in session.

To test it whether is it related to post method I created test and test1 methods. in this method everything works fine. Therefore I am thinking it is related to post.

Am I missing a step to accept session cookies for post requests?



via necilAlbayrak

Can't establish TCP Peer connection

UDP - Sent: tracker.leechers-paradise.org:6969 :: 0 0 4 17 27 10 19 80 0 0 0 0 0 60 0 0
UDP - Received: 87.233.192.220:6969 :: 0 0 0 0 0 60 0 0 0 0 52 55 7 74 0 0
UDP - Sent: tracker.leechers-paradise.org:6969 :: 0 0 52 55 7 74 0 0 0 0 0 1 0 0 0 0 43 44 50 0 0 79 0 0 31 58 23 27 0 0 0 35 0 0 0 1 0 48 33 31 0 30 0 0 82 0 0 82 37 0 0 0 2 0 80 6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0
UDP - Received: 87.233.192.220:6969 :: 0 0 0 1 0 0 0 0 0 0 7 81 0 0 0 1 0 0 0 11 43 0 0 0 0 33 29 0 26 0 64 19 0 0 0 0 0 82 0 71 0 0 61 0 0 0 0 47 75 0 81 38 0 57 0 5 0 48 0 47 41 0 0 0 80 33 0 0 58 6 33 85 69 0 54 9 0 45 41 0
TCP - Establishing connection: 84.9.208.69:6881

events.js:163
      throw er; // Unhandled 'error' event
      ^

Error: connect ECONNREFUSED 84.9.208.69:6881
    at Object.exports._errnoException (util.js:1050:11)
    at exports._exceptionWithHostPort (util.js:1073:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1093:14)

This is the decoded announce response

1 // Event (Announce)
4197152652 // Random request ID
1953 // Interval
1 // Leechers
17 // Seeders
[
  [ '173.239.236.71', 30075 ],
  [ '187.113.172.46', 25079 ],
  [ '213.109.239.162', 24194 ],
  [ '41.205.38.172', 25625 ],
  [ '67.184.203.252', 32307 ],
  [ '69.114.27.207', 30474 ],
  [ '88.6.51.133', 27066 ],
  [ '92.221.128.51', 53925 ],
  [ '103.255.145.186', 45271 ],
  [ '84.9.208.69', 6881 ]
] // Peers

I've been trying to figure out what's going on, but there are no errors and I've not found documentation on an explanation.

The connection is either closed after connecting, or simply refused.

My handshake seems to be valid, but even if it wasn't, the connection is being closed/refused before I even get the chance to write the handshake.

What type of reason could be attributing to this behaviour?



via Tobiq

A convenient way to update a project on server

There is a project (node.js - although it's not important), which is developed on the local machine and is periodically transferred to the server. In principle, I could simply erase the project folder on the server each time and replace it with a new one - uploaded from the local machine.
The matter is, that some folders (specifically: node_modules), I do not need to rewrite. So I have to manually create an archive, excluding unnecessary folders from it. And on the server, too, pre-erase everything except for some folders and only then replace.
How can I automate this procedure?
(On the local machine - windows, on the server - Linux)



via s976

how to add authentication to aws api gateway call in NodeJS

I'm calling AWS APi Gateway from node, using the following options:

var post_options = {
        host: 'myurl.execute-api.us-west-2.amazonaws.com',
        port: '443'
        path: '/staging/api',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': Buffer.byteLength(post_data)
        }
    };

The call is made in the following way:

http.post(post_options, post_data, function(res){
            res.setEncoding('utf8');
            res.on('data', function(chunk) {
                console.log(chunk);
            });
        });

The response I get back is:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Bad request.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: Yl1rUhK7Bmaq57ckHvK1E32tqNqDs4GC078yek3_23_RMefXUGJAdA==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>
name: undefined
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Bad request.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: nJ3dotCRum8XudR6v0PinqzDjjPCX3N5TmoM2fNQSJK9BLn8jJEWqg==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>

I think, I'm getting "Bad request" because I did not pass any authentication information to my call. What is the proper syntax to add such auth information?



via Eugene Goldberg

NodeJS 7.x - Cannot use ES6 (import, export, etc) [duplicate]

This question already has an answer here:

I have a problem with being unable to use ES6 features such as import, export keywords.

NodeJS throws an unexpected token error for imports/exports.

I also have issues with lambdas.

NodeJS: v7.10.0. (I also have tried v8)

Operating System: Ubuntu 16.04

I only have this issue on my laptop, not my desktop (also running Ubuntu 16.04). Both use NodeJS repo with the following command:

curl -sL https://deb.nodesource.com/setup_7.x | sudo -E bash -



via Novalis

Passport.js crashes the server when entering the wrong password

My passport.js file looks like this.

    passport.use(new LocalStrategy({
    usernameField: 'usernameOrEmail',
    passwordField: 'password',
    passReqToCallback: true,
    session: true
  },
  function(req, usernameOrEmail, password, done) {
    bookshelf.transaction((t) => {
      return User.login(usernameOrEmail, password, req, t)
    })
    .then((user) => done(null, user))
    .catch((err) => {
      if (err.message == 'EmptyResponse') {
        err.message = "The username you have requested does not exist. Kindly contact your administrator";
      }
      done(null, false, { message: err.message })
    });
  }
));

Also this is how i login

router.get('/login', (req, res, next) => {
  res.locals.notifications = []
  res.render('login');
});
router.post('/login',
  passport.authenticate('local', {
    successReturnToOrRedirect: '/dashboard',
    failureRedirect: '/login',
    failureFlash: true
  }));

The passport js is correctley logging in if the username and password is correct. also it is redirecting correctley if the username or password is wrong or both but it crashes the server how can i figure out what is going wrong and where? Or how to fix this?.



via arunwebber

createReadStream pipe not working in electron 1.6

createReadStream pipe not working in electron 1.6. It was working for 1.3 version. But now when i updated the version of electron, it not working. Please refer the code below.

response.writeHead(200, {'Content-Type': 'video/mp4'});        

var rs = fs.createReadStream(queryData.video);  
rs.pipe(response);
response.end(); 

What's i am missing in the new version?



via Jay

I want to build web application but i don't know what to learn

I was learning front-end for a while. I can do good stuff with html css js. This time I want to build a web application for a friend. That takes order requests from the client and store it in a database. and send a notification email for admin and request number for the client.

Soo far I built a static website using html css bootstrap. I don't know how to take the order object and send it to database. Shall I learn nodejs to do it? I was trying to build a JSONObject and send it to url using AJAX. But I could not know how to do it.

Can Any one help me please :)



via Abdullah Hashim

how to properly invoke aws api gateway from node

I'm invoking aws api gateway in the following node code:

module.exports = function(app) {

    var apigClientFactory = require('aws-api-gateway-client').default;

    var querystring = require('querystring');



    var params = {
        //This is where any header, path, or querystring request params go. The key is the parameter named as defined in the API
        userId: '1234'
    };
    var additionalParams = {};

    app.get('*', function(req, res) {
        res.sendfile('./public/index.html');
    });

    app.post("/customerinfo", function(req, res) {
        console.log("name: " + req.body["customer_name"]);

        var body = {"async": true,
            "crossDomain": true,
            "url": "https://myurl.execute-api.us-west-2.amazonaws.com/staging/api",
            "method": "POST",
            "headers": {
            "cache-control": "no-cache"
        },
        "data": querystring.stringify(req.body["customer_name"])
    };
        var apigClient = apigClientFactory.newClient({
            apiKey: '1234',
            invokeUrl:'https://myurl.execute-api.us-west-2.amazonaws.com/staging/api'
        });

        apigClient.invokeApi(params, body, additionalParams)
            .then(function(result){
                // Add success callback code here.
            }).catch( function(result){
            // Add error callback code here.
        });
    });

};

I get the following error:

TypeError: method.toUpperCase is not a function
    at Object.apigClientFactory.newClient.apigClient.invokeApi (/Users/eugene/Desktop/dms/node_modules/aws-api-gateway-client/dist/apigClient.js:117:20)
    at Object.handle (/Users/eugene/Desktop/dms/app/routes.js:36:20)
    at next_layer (/Users/eugene/Desktop/dms/node_modules/express/lib/router/route.js:113:13)
    at Route.dispatch (/Users/eugene/Desktop/dms/node_modules/express/lib/router/route.js:117:5)
    at /Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:222:24
    at Function.proto.process_params (/Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:288:12)
    at next (/Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:216:19)
    at next (/Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:202:18)
    at Layer.staticMiddleware [as handle] (/Users/eugene/Desktop/dms/node_modules/serve-static/index.js:51:61)
    at trim_prefix (/Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:263:17)
    at /Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:225:9
    at Function.proto.process_params (/Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:288:12)
    at next (/Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:216:19)
    at Layer.methodOverride [as handle] (/Users/eugene/Desktop/dms/node_modules/method-override/index.js:75:5)
    at trim_prefix (/Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:263:17)
    at /Users/eugene/Desktop/dms/node_modules/express/lib/router/index.js:225:9

What the the most proper way to do this, to avoid getting this error?



via Eugene Goldberg

MongoDB query embedded document array

I have the following document:

{
    "_id" : ObjectId("59299670266cc82a042f3817"),
    "_userId" : ObjectId("590a08dba07c1a1bee87b310"),
    "name" : "My home",
    "floors" : [ 
        {
            "_id" : ObjectId("59299670266cc82a042f4541"),
            "name" : "Floor 1",
            "rooms" : [ 
                {
                    "_id" : ObjectId("59299670266cc82a042f4551"),
                    "name" : "Room 1",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4561"),
                            "name" : "Device 1"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4562"),
                            "name" : "Device 2"
                        }
                    ]
                },
                {
                    "_id" : ObjectId("59299670266cc82a042f4552"),
                    "name" : "Room 2",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4563"),
                            "name" : "Device 3"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4564"),
                            "name" : "Device 4"
                        }
                    ]
                }
            ]
        },
        {
            "_id" : ObjectId("59299670266cc82a042f4542"),
            "name" : "Floor 2",
            "rooms" : [ 
                {
                    "_id" : ObjectId("59299670266cc82a042f4553"),
                    "name" : "Room 1",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4565"),
                            "name" : "Device 5"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4566"),
                            "name" : "Device 6"
                        }
                    ]
                },
                {
                    "_id" : ObjectId("59299670266cc82a042f4554"),
                    "name" : "Room 2",
                    "devices" : [
                        {
                            "_id" : ObjectId("59299670266cc82a042f4567"),
                            "name" : "Device 7"
                        },
                        {
                            "_id" : ObjectId("59299670266cc82a042f4568"),
                            "name" : "Device 8"
                        }
                    ]
                }
            ]
        }
    ]
}

And I would like to get a list of all devices:

[
    {
        "_id" : ObjectId("59299670266cc82a042f4561"),
        "name" : "Device 1"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4562"),
        "name" : "Device 2"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4563"),
        "name" : "Device 3"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4564"),
        "name" : "Device 4"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4565"),
        "name" : "Device 5"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4566"),
        "name" : "Device 6"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4567"),
        "name" : "Device 7"
    },
    {
        "_id" : ObjectId("59299670266cc82a042f4568"),
        "name" : "Device 8"
    }
]

Is that possible with MongoDB?

I've tried it with aggregate and { $unwind: $floors.rooms.devices } or

{ $unwind: $floors }
{ $unwind: $floors.rooms }
{ $unwind: $floors.rooms.devices }

but the output is always empty. I don't know if I would get the output I want with $unwind at all.

Because I'm also using aggregate for other things a solution with it would be nice.



via Kiltarc

Why im getting error?

HI I am getting this error:

Error is:SyntaxError: Unexpected token ' in JSON at position 0 '{username:xyz,password:xyz}'

when i am calling server with this command:

{curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' http://localhost:8080

And my code is this:

var http = require('http');

function handle_incoming_request(req,res) {
console.log("Incoming Request:("+ req.method + ")" + req.url);
var json_data = "";

req.on(
    "readable",
    function(){
        var d = req.read();
        if(typeof d == 'string')
        json_data += d;
        else if(typeof d == 'object' && d instanceof Buffer)
        json_data += d.toString("utf8");
    });

    req.on(
        "end",
        function(){
            var out = "";
            if(!json_data)
            out = "I am no JSON"
            else {
                var json;
                try {
                    json = JSON.parse(json_data.toString("utf8"));
                } catch (err) {
                    console.log("Error is:" + err + "\n" + json_data);
                }
                if(!json)
                out = "Inavlid JSON" + json;
                else 
                out = "Valid JSON" + json_data;
            }
            res.end(out);
        }

    );
}


var s = http.createServer(handle_incoming_request);
s.listen(8080);



via Praveen Cool

How to select the file in native os pop using protractor

I am using protractor to automate my website. I have a scenario where need to upload the file clicking on upload button. When clicked on upload button then it renders the native os popup to select the file.

I tried to upload using below code without clicking on upload button.I think this approach is not correct as the user has to click on upload button and then select the file from native os popup.But still no luck

var fileToUpload = 'filePath';
var absolutePath = path.resolve(__dirname, fileToUpload);
element(by.id("creator--add-a-piece-empty")).sendKeys(absolutePath);

How to select the file in native os pop ? Is there any way to upload

Operating system - Mac siera



via Sharif

How to perform jquery ajax delete operation when delete is to remove an entry in mongodb?

I have a sample nodejs app with api in mondodb connected via mongoose. I get a bunch of responses something like this (Sinple Entry below)

    {
    name:"Task1"
    status:["pending"]
    0:"pending"
    __v:0
    _id:"592d6a398eb24a9ac85d1184"
   }

Now If I have to delete the entry I will create a route like:

/tasks/_id

which I have created in nodejs and it works fine. I need perform a delete operation using an ajax delete operation. How do I create a route like /tasks/_id in ajax that will delete the record. Below is my code.

     $.ajax({
      type:'DELETE',
      url:'/tasks/' + how to get _id here from mongodb, which could be available only on successful ajax operation,

        success : function( data) {
          console.log('success);
       },
      error : function() {
        console.log('error');

      }
    })



via Mike

Flow and function definitions

I'm trying to define a function signature in flow. I would expect the following code to throw an error but I'm not getting any error for this.

// function that applied a function to an array - just for numbers
const arrayMath = (func: () => number, arr: Array<number>):Array<Number> => arr.map(func);

// would expect this function to work OK with arrayMath
const square = (num: number): number => num * num;

// would expect this function to fail with arrayMath
const concatX = (str: string): string => `${str}X`;

// flow is not giving me an error here..
arrayMath(concatX, [1, 2, 3]);



via TimRich

Metadata scope does not support 'q' parameter

I am using the Node.js library for obtaining my Gmail inbox messages: https://www.npmjs.com/package/node-gmail-api

I have registered an oauth access token, but despite having done so I received this error when trying one of the examples: enter image description here

Can anyone explain to me what this means, and how to resolve it? I am a beginner to this whole thing.



via Christopher Aranadi

Using NodeJs on Drupal website with MySql DB

I would like to use NodeJS on my Drupal Website to pull data Async. Is it possible to host the website in GoDaddy? or we need to go AWS for hosting.



via ShivShankar

how to properly call AWS Api Gateway from node?

I'm trying to call AWS api gateway from NodeJS, using aws-api-gateway-client module.

Here is my code:

module.exports = function(app) {

    var apigClientFactory = require('aws-api-gateway-client').default;

    var querystring = require('querystring');

    var apigClient = apigClientFactory.newClient({
        apiKey: '1234'
    });

    var params = {
        //This is where any header, path, or querystring request params go. The key is the parameter named as defined in the API
        userId: '1234'
    };
    var additionalParams = {};

    app.get('*', function(req, res) {
        res.sendfile('./public/index.html');
    });

    app.post("/customerinfo", function(req, res) {
        console.log("name: " + req.body["customer_name"]);

        var body = {"async": true,
            "crossDomain": true,
            "url": "https://mystuff.execute-api.us-west-2.amazonaws.com/staging/api",
            "method": "POST",
            "headers": {
            "cache-control": "no-cache"
        },
        "data": querystring.stringify(req.body["customer_name"])
    };

        apigClient.invokeApi(params, body, additionalParams)
            .then(function(result){
                // Add success callback code here.
            }).catch( function(result){
            // Add error callback code here.
        });
    });

};

As soon as I start the node server, I get this error:

/Users/eugene/Desktop/dms/node_modules/aws-api-gateway-client/dist/apigClient.js:84
  var endpoint = /(^https?:\/\/[^\/]+)/g.exec(invokeUrl)[1];
                                                        ^

TypeError: Cannot read property '1' of null
    at Object.apigClientFactory.newClient (/Users/eugene/Desktop/dms/node_modules/aws-api-gateway-client/dist/apigClient.js:84:57)
    at module.exports (/Users/eugene/Desktop/dms/app/routes.js:7:40)
    at Object.<anonymous> (/Users/eugene/Desktop/dms/server.js:26:24)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.runMain [as _onTimeout] (module.js:441:10)
    at Timer.listOnTimeout (timers.js:92:15)

What is the proper way to call AWS Api Gateway from Node?



via Eugene Goldberg

Sending email messages using nodemailer

I am using nodemailer to send email messages from my server (Node.js) and currently, i'm using this generic function:

// Generic Inner Function - Send Email
exports.sendEmail = function(email, message, emailType){
    if((email)&&(message)&&(emailType)){
        var subject;
        if(emailType == "signUp")
            subject = "Welcome to my site - 🙂";
        if(emailType == "forgotPass")
            subject = "Recovery Password from my site - 🔑";
        if(emailType == "newResult")
            subject = "We have Found New Results for you - 🛒";
        if(emailType == "arrivedPrice")
            subject = "Product Arrived - 🏴";
        if(emailType == "tonePrice")
            subject = "Product Arrived tone - 🏳️";

        console.log("Send Email to: "+email+" / Email Type: "+emailType);
        'use strict';
        const nodemailer = require('nodemailer');

        // create reusable transporter object using the default SMTP transport
        let transporter = nodemailer.createTransport({
            service: 'gmail',
            auth: {
                user: 'tester@gmail.com',
                pass: 'test'
            }
        });

        // setup email data with unicode symbols
        let mailOptions = {
            from: '"tom 🏏" <tester@gmail.com>', // sender address
            to: email, // list of receivers
            subject: subject, // Subject line
            text: message, // plain text body
            html: '<b>'+message+'</b>' // html body
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return console.log(error);
            }
            console.log('Message %s sent: %s', info.messageId, info.response);
        });
    }
};

Now, I was creating a new HTML messages that I want to send according to the action the user is doing and I am struggling with how to do it. I want to use Nodemailer to do this operation and I didn't find information over the web.

Sample of the HTML message:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>A Simple Responsive HTML Email</title>
  <style type="text/css">
  body {margin: 0; padding: 0; min-width: 100%!important;}
  img {height: auto;}
  .content {width: 100%; max-width: 600px;}
  .header {padding: 40px 30px 20px 30px;}
  .innerpadding {padding: 30px 30px 30px 30px;}
  .borderbottom {border-bottom: 1px solid #f2eeed;}
  .subhead {font-size: 15px; color: #ffffff; font-family: sans-serif; letter-spacing: 10px;}
  .h1, .h2, .bodycopy {color: #153643; font-family: sans-serif;}
  .h1 {font-size: 33px; line-height: 38px; font-weight: bold;}
  .h2 {padding: 0 0 15px 0; font-size: 24px; line-height: 28px; font-weight: bold;}
  .bodycopy {font-size: 16px; line-height: 22px;}
  .button {text-align: center; font-size: 18px; font-family: sans-serif; font-weight: bold; padding: 0 30px 0 30px;}
  .button a {color: #ffffff; text-decoration: none;}
  .footer {padding: 20px 30px 15px 30px;}
  .footercopy {font-family: sans-serif; font-size: 14px; color: #ffffff;}
  .footercopy a {color: #ffffff; text-decoration: underline;}

  @media only screen and (max-width: 550px), screen and (max-device-width: 550px) {
  body[yahoo] .hide {display: none!important;}
  body[yahoo] .buttonwrapper {background-color: transparent!important;}
  body[yahoo] .button {padding: 0px!important;}
  body[yahoo] .button a {background-color: #00ae9d; padding: 15px 15px 13px!important;}
  body[yahoo] .unsubscribe {display: block; margin-top: 20px; padding: 10px 50px; background: #2f3942; border-radius: 5px; text-decoration: none!important; font-weight: bold;}
  }

  /*@media only screen and (min-device-width: 601px) {
    .content {width: 600px !important;}
    .col425 {width: 425px!important;}
    .col380 {width: 380px!important;}
    }*/

  </style>
</head>

<body yahoo bgcolor="#f6f8f1">
<table width="100%" bgcolor="#f6f8f1" border="0" cellpadding="0" cellspacing="0">
<tr>
  <td>
    <!--[if (gte mso 9)|(IE)]>
      <table width="600" align="center" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td>
    <![endif]-->
    <table bgcolor="#ffffff" class="content" align="center" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td bgcolor="#c7d8a7" class="header">
          <table width="70" align="left" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td height="70" style="padding: 0 20px 20px 0;">
                <img class="fix" src="email/logoC.png" width="70" height="70" border="0" alt="" />
              </td>
            </tr>
          </table>
          <!--[if (gte mso 9)|(IE)]>
            <table width="425" align="left" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <td>
          <![endif]-->
          <table class="col425" align="left" border="0" cellpadding="0" cellspacing="0" style="width: 100%; max-width: 425px;">
            <tr>
              <td height="70">
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td class="subhead" style="padding: 0 0 0 3px;">
                      Tester
                    </td>
                  </tr>
                  <tr>
                    <td class="h1" style="padding: 5px 0 0 0;">
                      Chasing For You
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
          <!--[if (gte mso 9)|(IE)]>
                </td>
              </tr>
          </table>
          <![endif]-->
        </td>
      </tr>
      <tr>
        <td class="innerpadding borderbottom">
          <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td class="h2">
                Welcome to Cricket !
              </td>
            </tr>
            <tr>
              <td class="bodycopy">
              We're so happy you have joined our family!!!
              <br/>
              We founded Tester because we wanted to create a trustworthy app 
              </td>
            </tr>
          </table>
        </td>
      </tr>
      <tr>
        <td class="innerpadding borderbottom">
          <table width="115" align="left" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td height="115" style="padding: 0 20px 20px 0;">
                <img class="fix" src="email/testimonial-bg.jpg" width="115" height="115" border="0" alt="" />
              </td>
            </tr>
          </table>
          <!--[if (gte mso 9)|(IE)]>
            <table width="380" align="left" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <td>
          <![endif]-->
          <table class="col380" align="left" border="0" cellpadding="0" cellspacing="0" style="width: 100%; max-width: 380px;">
            <tr>
              <td>
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td class="bodycopy">
                        Tester offers a Chrome extension that lets you set a.
                    </td>
                  </tr>
                  <tr>
                    <td style="padding: 20px 0 0 0;">
                      <table class="buttonwrapper" bgcolor="#00ae9d" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                          <td class="button" height="45">
                            <a href="#">GET THE EXTENSION</a>
                          </td>
                        </tr>
                      </table>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
          <!--[if (gte mso 9)|(IE)]>
                </td>
              </tr>
          </table>
          <![endif]-->
        </td>
      </tr>
            <tr>
        <td class="innerpadding borderbottom">
          <table width="115" align="left" border="0" cellpadding="0" cellspacing="0">
            <tr>
              <td height="115" style="padding: 0 20px 20px 0;">
                <img class="fix" src="email/mobile.jpg" width="115" height="115" border="0" alt="" />
              </td>
            </tr>
          </table>
          <!--[if (gte mso 9)|(IE)]>
            <table width="380" align="left" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <td>
          <![endif]-->
          <table class="col380" align="left" border="0" cellpadding="0" cellspacing="0" style="width: 100%; max-width: 380px;">
            <tr>
              <td>
                <table width="100%" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td class="bodycopy">
                         Tester is also offers an Android App that lets you.
                    </td>
                  </tr>
                  <tr>
                    <td style="padding: 20px 0 0 0;">
                      <table class="buttonwrapper" bgcolor="#00ae9d" border="0" cellspacing="0" cellpadding="0">
                        <tr>
                          <td class="button" height="45">
                            <a href="#">GET THE APP</a>
                          </td>
                        </tr>
                      </table>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
          <!--[if (gte mso 9)|(IE)]>
                </td>
              </tr>
          </table>
          <![endif]-->
        </td>
      </tr>
      <tr>
        <td class="innerpadding borderbottom">
          <img class="fix" src="email/coffee3.jpg" width="100%" border="0" alt="" />
        </td>
      </tr>
<!--
      <tr>
        <td class="innerpadding bodycopy">
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tempus adipiscing felis, sit amet blandit ipsum volutpat sed. Morbi porttitor, eget accumsan dictum, nisi libero ultricies ipsum, in posuere mauris neque at erat.
        </td>
      </tr>
-->
      <tr>
        <td class="footer" bgcolor="#44525f">
          <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
              <td align="center" class="footercopy">
                &reg; Copyright &copy; 2017 - Designed &amp; Developed by Cricket Team <br/>
                <a href="#" class="unsubscribe"><font color="#ffffff">Unsubscribe</font></a>
                <span class="hide">from Test newsletter</span>
              </td>
            </tr>
            <tr>
              <td align="center" style="padding: 20px 0 0 0;">
                <table border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td width="37" style="text-align: center; padding: 0 10px 0 10px;">
                      <a href="http://www.facebook.com/">
                        <img src="email/facebook.png" width="37" height="37" alt="Facebook" border="0" />
                      </a>
                    </td>
                    <td width="37" style="text-align: center; padding: 0 10px 0 10px;">
                      <a href="http://www.twitter.com/">
                        <img src="email/twitter.png" width="37" height="37" alt="Twitter" border="0" />
                      </a>
                    </td>
                  </tr>
                </table>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
    <!--[if (gte mso 9)|(IE)]>
          </td>
        </tr>
    </table>
    <![endif]-->
    </td>
  </tr>
</table>
</body>
</html>



via drorAlfasi

How to wath screen of device connected in same wifi NODE.JS

I want to get(and spy) screen of device which is connected in my wifi , with node.js in real time



via Albert Hovhannisyan

Node.js: "process run out of memory"

I have the following code which leads to the error: FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

It doesn't make any difference whether I set --max_old_space_size=4096 (or bigger numbers) or not. I have 16 GB RAM on my PC.

System: win10/node.js 6.9.2/mongodb 3.4

I have over 16 000 000 messages in the "chatModel". With a smaller amount of messages the code works.

Do you have any suggestions how to solve the problem/optimize the code?

function sortOutMessages(){

var atSymbol = "@";
var rgx = new RegExp("^\\" +atSymbol);


chatModel.find({messageContent: rgx}, function (err, doc){

    var docs = doc;
    var docsLength = docs.length;

    for (var i =0; i<docsLength;i++) {
        var directedMessagesObj = new directedMessagesModel
        ({
            timeStamp: docs[i].timeStamp,
            channelName: docs[i].channelName,
            userName: docs[i].userName,
            userID: docs[i].userID,
            messageContent: docs[i].messageContent,
            messageLength: docs[i].messageLength,
            subscriber: docs[i].subscriber,
            turbo: docs[i].turbo,
            moderator: docs[i].moderator
        });

        directedMessagesObj.save({upsert:true}, function (err) {
            var fs = require('fs');
            if (err) {
                    fs.appendFile("undefinedLog.txt", "error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n")
                    loggerWinston.warn("error at " + new Date().toLocaleString() + " directedMessagesObj.save " + "\r\n");
                    return console.log(err);
            }

        });
    }

});



}



via dmtrshpv

Remote debug node in docker container - sourcemaps in WebStorm

I have problems debugging contenerized application using WebStorm (or IntelliJ) remote debugging option which works perfect when trying to remote debug application running locally.

Here are the relevant parts of my gulp config file:

gulp.task("mainCompile", () =>
    gulp.src(`${config.src.main.baseDir}/**/*.js`, {base: "./src"})
        .pipe(plugins.sourcemaps.init())
        .pipe(plugins.babel())
        .pipe(plugins.sourcemaps.write(".", {
          includeContent: false,
          sourceRoot: "../src"
        }))
        .pipe(gulp.dest(config.build.baseDir))
);

gulp.task("nodemon", ["copyResources", "compile"], () =>
    plugins.nodemon({
      execMap: {
        js: "node --debug-brk"
      },
      script: path.join(config.build.mainDir, "index.js"),
      ext: "js yaml",
      delay: 2500,
      debug: true,
      verbose: true,
      watch: config.src.main.baseDir,
      tasks: ["copyNonJs", "yamlToJson", "compile"]
    })
);

And the part of compose config. As you can see I mount the project root at /app in the container.

server:
    image: justmarried/jmserver:development-latest
    build:
      context: .
      dockerfile: containers/develop/Dockerfile
    ports:
      - 2701:2701
      - 5858:5858
    volumes:
      - ./:/app

Remote debugger attaches but stops only for breakpoints defined in index.js (or if I put a breakpoint inside "build" dir which is not what I want). When the app is fully loaded I get this:

webstorm

As you can see index.js gets mapped perfectly but none of the other files do. Tried to inline code into sourcemaps but it didn't help. Is it a bug in WebStorm (newest, 2017.1.3)?



via kboom

Passing command line (npm) arguments trough multiple levels

I'm currently working with angular-webpack2-starter which has already predefined npm tasks, but they don't work properly (at least for me).

Here you can see complete package.json

Excerpt with commands I'm using

"scripts": {
  "sass": "node-sass \"src/app/styles.scss\" \"src/app/styles.css\" --include-path node_modules --output-style compressed -q",
  "sass:watch": "node-sass -w  \"src/app/styles.scss\" \"src/app/styles.css\"  --include-path node_modules --output-style compressed -q",
  "server:universal": "nodemon dist/server.js",
  "clean:dist": "npm run rimraf -- dist .awcache",
  "build:universal": "npm run build:universal:prod",
  "build:universal:prod": "npm run clean:dist && npm run sass && webpack",
  "watch:universal": "npm-run-all -p -r \"build:universal -- --watch\" sass:watch",
  "universal:watch": "npm run build:universal && npm-run-all -p -r watch:universal server:universal"
}

The problem seems to be in
"watch:universal": "npm-run-all -p -r \"build:universal -- --watch\" sass:watch", , because --watch doesn't propagate to webpack command.

If I run build:universal -- -- --watch it works as expected.

Note the double (-- --)

Is it the right way to run it like this ?



via Stevik

How to make module (such as bcrypt) available globally in Express?

I have several "routes" files where I import modules like this:

var bcrypt = require('bcryptjs');

I have attempted to make bcrypt available globally by importing it into my main app js and then using an app.use() something like this:

var bcrypt = require('bcryptjs');
app.use(bcrypt); // clearly not right, app crashes

I've tried a variety of things here. Should I just stick with importing this into every file separately or is there a good way to make this module available globally?



via Alan

Google Cloud Functions - Repository deployment - Reading Setting File

This might be more of a best practice question, but I am deploying a cloud function in GCloud via GitHub repo to multiple environments, each with their own secrets for database up that this cloud function will write to (elastic search). How do I get the function to access a settings file in their own respective environments? Using Node.js, FYI.



via Greg Reese

Node.js. How to start two separate process(servers) running parrallel in one express application?

I have one express application. I need to add another process, that should be running separately from the main application, but share the libs/modules that the first app has. Now I'm struggling with finding the best solution for that? What is the best practices in doing such, guys?



via Ігор Косандяк

NodeJS not exiting after readline

Node JS process is not exiting after reading file via readline under Windows:

const readline = require('readline');
const fs = require('fs');
const rs = fs.createReadStream('../data/lorem.txt');
const rl = readline.createInterface({
    input: rs
});

rl.on('line', function(line) {
    console.log(line);
});

setTimeout(function () {
    rl.close();
    // tried these too:
    // rs.close();
    // rs.destroy();
},1000);

I don't want to use process.exit(0) because I am processing multiple files, and the fact that node is not exiting tells me that it is holding up some resources. How do I release them properly?



via amaksr

sending data from node.js webserver to arduino

I'm trying to send data from node.js webserver to arduino using serialport. for example, when I send value from webserver, arduino takes the value and if temperature is lower than the value, led is on or if temperature is higher than the value, led is off. I successfully send data to arduino but led is not working. This is my arduino code and node.js code.

...
        function openPort() {
              var temp = temperature; 
                console.log('port open');
                  console.log('baud rate: ' + myPort.options.baudRate);

            function sendData() {

            //myPort.write(temp.toString());
        for(var i=0; i<temp.length; i++) {
          myPort.write(new Buffer(temp[i], 'ascii'), function(err, results) {
            });

          }

            console.log('Sending ' + temp + ' out the serial port');
        }
        setTimeout(sendData, 500);


       }
...



float temperature;
float temp1;
float temp2;
float lm35Pin1 = A0;
float lm35Pin2 = A1;
int led = 13;
String inData = "";

void setup()  
{
  pinMode(led, OUTPUT);
  analogReference(INTERNAL);
  Serial.begin(9600);
}

void loop()  
{
  temp1 = analogRead(lm35Pin1);
  temp2 = analogRead(lm35Pin2);
  temperature = ((temp1 / 9.31) + (temp2 / 9.31)) /2 ;

  while (Serial.available() > 0) {
    long received = Serial.parseInt();
    inData.concat(received);
  }

  if(temperature <= inData.toInt()) {
    digitalWrite(led, HIGH);
  }
  if(temperature > inData.toInt()) {
    digitalWrite(led, LOW);
  }

  Serial.println(temperature);
  Serial.println(inData);
  inData = "";
  delay(3000);
}



via Byunghun Jang

Cannot enqueue Query after invoking quit

According to the Node MySQL documentation (https://github.com/mysqljs/mysql#introduction):

Every method you invoke on a connection is queued and executed in sequence.

and

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

Nevertheless, the code below doesn't work, because the connection.end() method is called before the SQL queries can run. If I comment out the connection.end() line, it works, but the script hangs (doesn't close/end) when it completes, requiring me to hit ctrl-c to end it.

If I move the MySQL connection object and the connection.end() call into the lineReader.createInterface block, it works - the script correctly terminates at the end...but it's creating a new connection for every INSERT statement.

It doesn't seem right to close and reconnect each time like that. Am I misunderstanding the Node MySQL documentation? Is there a better way?

let lineReader  = require('readline');
let file        = require('fs');
let mysql       = require('mysql');

let connection  = mysql.createConnection({
    host: '127.0.0.1',
    port: 33060,
    user: 'homestead',
    password: 'secret',
    database: 'sentinel',
});

lineReader.createInterface({
        input: file.createReadStream('proxies/proxies.txt')
    }).on('line', function (line) {
        let ary = line.split(/[:, ]/);
        let insert_sql;

        if (typeof ary[2] !== 'undefined' && typeof  ary[3] !== 'undefined') {
            insert_sql =
                'INSERT INTO proxies (host, port, username, password) ' +
                'VALUES ("' + ary[0] + '", "' + ary[1] + '", "' + ary[2] + '", "' + ary[3] + '")';
        } else {
            insert_sql =
                'INSERT INTO proxies (host, port) ' +
                'VALUES ("' + ary[0] + '", "' + ary[1] + '")';
        }

        connection.query(insert_sql, function (error, results, fields) {
            if (error) {
                console.log('error: ' + error);
            } else {
                console.log('success: ' + insert_sql);
            }
        });

    });

connection.end();



via CJG

How to use gulp in laravel on ubuntu 16.04

I have problem with gulp in my project. I installed node, npm, gulp and I created file gulpfile.js.

If I use command gulp never nothing happens.

I don't know what is incorrect.

Please help me.

My code for example:

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    sass = require('gulp-sass'),
    css_ = require('gulp-minify-css'),
    concat = require('gulp-concat'),
    livereload = require('gulp-livereload'),
    lr = require('tiny-lr'),
    clean = require('gulp-clean'),
    less = require('gulp-less'),
    server = lr();


var paths_css = {

    css: [  '/bower_components/AdminLTE/bootstrap/css/bootstrap.min.css',
            '/bower_components/AdminLTE/dist/css/AdminLTE.min.css',
            '/bower_components/AdminLTE/plugins/iCheck/flat/blue.css',
            '/bower_components/AdminLTE/plugins/morris/morris.css',
            '/bower_components/AdminLTE/plugins/jvectormap/jquery-jvectormap-1.2.2.css']
};


gulp.task('css', function() {
   return gulp.src(paths_css.css)
        .pipe(concat('css.css'))
        .pipe(sass())
        .pipe(gulp.dest('public/css/'));
});


gulp.task('default', ['css']);



via KTS

Can't find data from database after set it?

I have a piece of code which adds data to the database, then a function which gets the added data ID from the database. Problem is that, I get an error it couldn't be found, but it is in the database. How could I solve the problem?

[2017-06-03 18:01:25.855] [DEBUG] [default] - TypeError: Cannot read property 'id' of undefined

Here is how the function looks like

function getLastUser(hash, socket, user){
    query('SELECT * FROM users WHERE hash='+pool.escape(hash)+'', function(err, row){
        if(err){
            logger.error('Failed getting user hash: ' + user.name);
            logger.debug(err);
            socket.emit('message', {
                type: 'error',
                error: "Failed getting user hash"
            });
            return;
        }
        return row[0].id;
    });
}

Here the calling

getLastUser(hash, user, socket);



via Jordn

Import from subfolder of npm package

I've been working on creating a small library of React components for use in several other projects. I am publishing the package internally (using a private GitHub repository) and then including in another project. However, when I go to import from a subdirectory of the package I am not able to do so as the paths don't match.

The projects using the package all utilize webpack to bundle/transpile code as I am trying to avoid doing any building in the component library if possible.

Directory Structure

- package.json
- src/
  - index.js
  - Button/
    - index.js
    - Button.jsx
    - ButtonGroup.jsx
  - Header/
    - index.js
    - Header.jsx (default export)

package.json

...
"main": "./src/index.js",
"scripts": "",
...

src/Button/index.js

import Button from './Button';
import ButtonGroup from './ButtonGroup';

export default Button;

export { Button, ButtonGroup};

src/index.js

Is this file actually necessary if only importing from subdirectories?

import Button from './Button';
import ButtonGroup from './Button/ButtonGroup';
import Header from './Header';

export { Button, ButtonGroup, Header };

Other Project

// This project is responsible for building/transpiling after importing
import { Button, ButtonGroup } from 'components-library/Button';

Example

Material-UI is a library of React components that is used by requiring in the following fashion: import { RadioButtonGroup } from 'material-ui/RadioButton. I've tried to figure out how this works for them but to no avail yet.

Similar Questions

Questions

  1. Can I skip the src/ directory somehow in the import path?
  2. Can I skip any type of build phase in the package (so developers don't have to build before committing)?
  3. How does a package similar to material-ui handle this?


via Kendall Roth

Should I make NodeJS CHAT OR PHP CHAT Application?

I am creating a website where user can log in and chat! Those users information are set in mysql database! So i think it is compulsory to make chat application in php but is there a way to make chat in nodejs by connecting mongodb database with mysql database? Also suggest the performance speed of nodejs chat vs php chat!



via Fred

How to load resource from a relative path in a nodejs module?

In one of my NodeJS modules I need to access a file that is part of the module in an own folder (for unit tests). It tried __dirname in the calling file with a relative path to that resource file. This works when running from within vscode, but not whe executing npm test in a terminal. In that case the constructed path is one level off. How can that be? Is the __dirname value different, depending on the environment the execution starts?



via Mike Lischke

React-native UI frameowrk

Which is the best UI framework to use it with react-native ?

Nativebase or react-native-elements ?



via Ahmed Rebai

How to link an existing Angular 2 app to Nodejs Server?

I have an Angular 2 app with this structure :
Structure of my Angular app

Then in server side : Structure of server app

I see that there is 2 module dependencies folders, but I don't know which one I sould keep.

Here is my index.js file :

  const express = require('express');
  const path = require('path');
  const http = require('http');
  const bodyParser = require('body-parser');

  // Get our API routes
  //const api = require('./server/routes/api');

  const app = express();

  // Parsers for POST data
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));

  // Point static path to dist
  app.use(express.static(path.join(__dirname, 'client/portfolio')));

  // Set our api routes
  //app.use('/api', api);

  // Catch all other routes and return the index file
  app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'client/portfolio/src/index.html'));
  });

  /**
   * Get port from environment and store in Express.
   */
  const port = process.env.PORT || '3001';
  app.set('port', port);

  /**
   * Create HTTP server.
   */
  const server = http.createServer(app);

  /**
   * Listen on provided port, on all network interfaces.
   */
  server.listen(port, () => console.log(`API running on localhost:${port}`));

When I start server I get this message :

Loading AppComponent content here ...

But it stops here and doesn't render the Angular application.



via infodev

express.static only loading to index.html

I am trying to get the static files (images, js, css) which are all inside the public folder to be available to all my routes. I am able to ONLY load them to the index.html. The management.html files does not have access to the static files, I am getting 404 error on the Chrome console.

Folder Structure:

-app/  
---index.html
---management.html
---public/
------css/
------js/
------img/

server.js:

const express = require('express');
const path = require('path');

var app = express();

app.use(express.static(path.join(__dirname, 'public')));

app.get('/', function(req, res) {
    res.sendFile('index.html', {root: __dirname })
});

app.get('/management', function(req, res) {
    res.sendFile('management.html', {root: __dirname })
});

app.listen(3000);



via Timur Ozkul

Nodejs variable in name of variable

I want to define a variable called for example:

test = 1;
cookie_(content of test) = 1;

But when i change test to something like 2 it needs to make the new variable also cookie_2. How to do this?



via Noah van der Aa

How to run node express js server and angular 2 on same port

I am new nodejs and angular2. I need to know whether, Is it possible to run node express app serving as a backend and angular which serve as a frontend on same port. I followed Angular Quickstart tips on angular.io and created nodejs todo application but both are running on different port which raises the issue of Cross Origin Request Blocked Issue.

Please assist me. Your help be valuable.

Thanks



via Swapnil Deo

node http requests not executed concurrently if made from same browser

var http = require('http');
http.createServer(function (req, res) {
    setTimeout(function () {
        res.write("hello");
        res.end();
    }, 10000);
}).listen(8080);

this is my simple node server running on localhost.

Now if i hit this url localhost:8080 from two different browsers simultaneously, i get response at same time on both browsers i.e after around 10 secs.
But on other hand when i do so from two different tabs of chrome browser, it takes 10 secs for one tab and another 10 secs for 2nd tab.

Seems like requests are being processed one after another rather than simultaneously.
can somebody explain?



via user1050008

Do all AWS Node.js apps require the cluster module?

I was following the tutorial here, and noticed the index file (app.js) of the example code is quite different than a usual Express.js application. The code is wrapped inside the cluster module as follows:

// Include the cluster module
var cluster = require('cluster');

// Code to run if we're in the master process
if (cluster.isMaster) {

    // Count the machine's CPUs
    var cpuCount = require('os').cpus().length;

    // Create a worker for each CPU
    for (var i = 0; i < cpuCount; i += 1) {
        cluster.fork();
    }

    // Listen for terminating workers
    cluster.on('exit', function (worker) {

        // Replace the terminated workers
        console.log('Worker ' + worker.id + ' died :(');
        cluster.fork();

    });

// Code to run if we're in a worker process
} else {
    var AWS = require('aws-sdk');
    var express = require('express');
    var bodyParser = require('body-parser');
    // the usual code ..
}

Is this necessary, or can I just deploy the regular code without the cluster module, like this:

var AWS = require('aws-sdk');
var express = require('express');
var bodyParser = require('body-parser');
// the usual code ..

Thanks,



via jeff