Node.js

168

Solutions

302

Contributors

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Share tech news, updates, or what's on your mind.

Sign up to Post

I'm working through a tutorial on Node where I've got an MCV architecture going on.

This is the relevant piece of my Controller:

const Product = require("../models/product");

exports.postAddProduct = (req, res, next) => {
  const product = new Product(req.body.title); // right here I'm establishing a new instance of my Product class and I'm passing a variable into that class that's coming from my form
  product.save();
  res.redirect("/");
};

Open in new window


This is the relevant portion of my Model:

const products = [];

module.exports = class Product {
  constructor(title) {
    this.title = title;
  }

  save() {
    products.push(this);
  }

Open in new window


What you see works and there's nothing about it that's especially confusing, but I did have a question.

When I saw this syntax, I was able to understand its logic based on my experience with PHP, as far as creating an instance of a class and having a constructor sitting at the top of that class.

All good.

But that I started looking at it a little bit closer and noticed that I was passing a variable into a class.

You don't do that with PHP do you?

I know that's a bizarre question, but when I think of constructors in PHP, I'm thinking of defining some properties and the attaching values to those properties that I can then access throughout my class depending on their visibility.

But do you  / can you pass variables into a class in PHP?

There you go! A random question to kick off your Thursday morning...
0
Price Your IT Services for Profit
Price Your IT Services for Profit

Managed service contracts are great - when they're making you money. Yes, you’re getting paid monthly, but is it actually profitable? Learn to calculate your hourly overhead burden so you can master your IT services pricing strategy.

Looking for examples of modern distributed web applications.

Hello all,

I am trying to understand some examples of complex modern web applications which are used in companies like Kroger , Office Depot or financial companies like Freddie Mac , Fannie Mae etc.

If someone wants to one day get ready to work in these companies as a junior / senior programming what all things they should know

this is a very broad question but some answers will help me ask some more targetted specific questions

I am very interested in learning about designing and making Enterprise Applications

thanks
-anshu
1
Getting my Angular 4 application running again on my MacBook

I have not run this app for months and also upgraded my MacOS to Mojave weeks ago. And now I need to run my Angular 4 program from Visual Studio Code.

I have forgotten exactly how to force it into debug mode. Or, even run without debugging mode. I need to test if it still works.

How can I do this?

I assume I need to open Terminal and start the Node Angular server. How do I do this?

Thanks.
0
I want to build a http REST service in node js. I have few Javascript files.

how can i call the different functions in these different javascript files, from say one server.js file that I write in node js for the REST service?
0
Here is a part of my code:

if (url === "/message" && method === "POST") {
    const body = [];
    req.on("data", chunk => {
      console.log(chunk);
      body.push(chunk);
    });
     [b]req.on("end", () => {[/b]
      const parsedBody = Buffer.concat(body).toString();
      const message = parsedBody.split("=")[1];
      fs.writeFile("message.txt", message, err => {
        res.statusCode = 302;
        res.setHeader("Location", "/");
        return res.end();
      });
    });
  }
  res.setHeader("Content", "text/html");
  res.write("<html");
  res.write("<head><title>My First Page</title></head>");
  res.write("<body><h1>Yo, dog!</h1></body>");
  res.write("</html>");
  res.end();
});

Open in new window


This is what I understand: The order in which this code is being fired is:

req.on("end", () => { -> Event Listener is registered, but not triggered until the end of the overall process

res.setHeader("Content", "text/html"); -> this will fire before the "req.on" because while "req.on" is seen by the process, it's fired asyncronously so it's not processed until the very end.

That's going to be a problem in the the headers have already been set, which result in an error.

However, if I do this:

return req.on("end", () => { - then I don't get an error and the code runs fine.

Why? What's significant about "return" that it allows the code to run in a healthy manner? It seems like it's still and Event Listener and, as far as the Call Stack, it's not being fired until the end and I would expect the same error. But there is no error and I want to understand why.

What do you think?
0
This is a node.js application. I have a route like:
router.get('/', ...));

Open in new window

that I want to render
deviceController.getDevices

Open in new window

if
const devices = await Device.find({ owner: req.user._id });

Open in new window

is truthy, and
modelController.getModels

Open in new window

 if not.

What is the best way to do this?

getDevices is something like:
exports.getDevices = async (req, res) => {
  ...
  res.render('devices', { title: 'My Devices', devices });
};

Open in new window

getModels is something like:
exports.getModels = async (req, res) => {
  ...
  res.render('models', { title: 'Models', models, page, pages, count });
};

Open in new window


So I want the "/" route to render "devices" if the user has devices, "models" if not. I tried the below but it seems like totally the wrong approach.
router.post('/login', authController.login, deviceController.hasDevice);

exports.login = (req, res, next) => {
  passport.authenticate('local', {
    failureRedirect: '/login',
    failureFlash: 'Failed Login'
 });
 next();
};

exports.hasDevice = async (req, res) => {
  const devices = await Device.find({ owner: req.user._id });
  if (!devices.length) {
    res.render('store', { title: 'Store' });
  } else {
    res.render('devices', { title: 'My Devices', devices });
  }
};

Open in new window


Can anyone point me in the right direction?
0
Here's my code:

const fetchData = callback => {
  setTimeout(() => {
    callback("Done!");
  }, 1500);
};

setTimeout(() => {
  console.log("Timer is done!");
  fetchData(text => {
    console.log(text);
  });
}, 2000);

console.log("Hello");
console.log("Hi");

Open in new window


I'm taking a course in Node and I'm new to Javascript so I'm having to do a lot of "catch up...!"

I want to understand the flow of what you see above, specifically in the context of the callback function.  I'm going to explain what you see above and why it works the way that it does. What I want as an "answer" is a validation in terms of whether or not I explained it correctly and, if not, correct my logic.

First of all: "const" is a fixed variable that can't be reassigned. In this case, the variable is a function. It's not an anonymous function so it's not going to fire unless it's called.

Secondly, the "setTimeout" function is an anonymous function and it's going to fire right out of the chute. The first thing it's going to do after 2 seconds is write "Timer is done" to the console. The next thing it;s doing is calling the "fetchData" function which is expecting a parameter. That parameter, called "callback" in this case is this:

text => {
    console.log(text);
  }

So, text is going to be defined as "Done" after a second and a half and there you have it!

Is that an accurate explanation? Am I missing anything?
0
I have a products and category collection. I want to query both of them and send the data through one controller so I can display products and categories in the same view.

This seems to work but I am not sure if it is the correct way of doing it? If not, please could you you advise me on a more appropriate way.

exports.getIndex = (req, res, next) => {
  Product.find({ status: "approved" })
    .sort({ createdAt: -1 })
    .then(products => {
      Category.find({})
        .sort({ catName: 1 })
        .then(category => {
          res.render("shop/index", {
            pageTitle: "My home page",
            path: "/",
            prods: products,
            category: category
          });
        });
    })
    .catch(err => {
      console.log(err);
    });
};

Open in new window

0
I know this question is asked a lot so please don't downvote or mark as duplicate. I have looked on google and on stack overflow but most answers talk about using passport which I am not using and a lot of the questions I looked at are for php.

I have a login button on a product detail page. If a user clicks on it they are redirected to the login page and after login I want to send them back to the product detail page.

In my starting point (app.js) I am setting a session variable for what I think is the referrer. (Should be like php $_SERVER['REQUEST_URI')

app.use((req, res, next) => {
    req.session.lastPageOn = req.get('Referrer');
    next();
});

Open in new window


In my login script I have:

if (req.session.lastPageOn) {
    res.redirect(req.session.lastPageOn)
} else {
    res.redirect('account/dashboard');
}

Open in new window


But every time I login in I get redirected to the login page as that was the last page I was on before logging in! So, it doesn't seem like req.get('Referrer'); is the right thing to use or my implementation is incorrect.
0
I have a problem where a record is updating in the database even when validation fails which should obviously not happen. I suspect it is the way I have structured my then() and catch() blocks but I'm not 100% sure.

exports.postEditListing = (req, res, next) => {
    const updatedTitle = req.body.title;
    const updatedDescription = req.body.description;
    const updatedCategory = req.body.category;
    const image = req.file;
    const productId = req.body.productId;
    const updatedSlugTitle = slugify(updatedTitle, {
        lower: true,
        remove: /[*+~.()'"!:@]/g
    });
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        Category.find({ catName: { $ne: updatedCategory } })
        .then(cats =>{
            return res.status(422).render('account/edit-listing', {
                pageTitle: 'Edit Listing',
                path: '/account/edit-listing',
                product: {
                    title: updatedTitle,
                    _id: productId,
                    category: updatedCategory,
                    description: updatedDescription
                },
                errorMessage: errors.array(),
                successMessage: null,
                pendingCount: req.pending,
                approveCount: req.approved,
                rejectCount: req.rejected,
                userId: req.user._id,
                cats: cats
            });
        })

    }
    Product.findById(productId)
        .then(product

Open in new window

0
Microsoft Azure 2017
LVL 13
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

I am trying to count database records in mongoDB (using mongoose) where records have a status of pending and approved as well as rejected. So, I am basically trying to get a result where I can show a count of each and display it in my view ie:

Pending: 35
 Approved: 97
 Rejected: 12

And I want to hold these in variables that I can use in different places ie:

const pending = ....
const approved = ....
const rejected = .....

I have tried to use the aggregate function and run a loop which gets me all the data I need but I don't know how to actually get the data into the three variables like above.

    Product.aggregate([
        { $group: { _id: { status: "$status" }, totalStatus: { $sum: 1 } } }

    ])

Open in new window


The above code gives me back this (I have no rejected values yet)

[
    {
        _id: {
            status: 'pending'
        },
        totalStatus: 15
    },
    {
        _id: {
            status: 'approved'
        },
        totalStatus: 27
    }
  ]

Open in new window


I then ran a loop and restructured the data:

        .then(status => {
            for (const current of status) {
                const [status, total] = [current._id.status, current.totalStatus];
                console.log(status + ': ' + total);
            }
            next();
        })

Open in new window


That gives me:

pending: 15
approved: 27

But it still isn't what I actually want. I need to get those values into their own variables. How can I do that?
1
Need best websites (e.g. plus utube video if possible) for upgrading an Oracle (3) node RAC database under Solaris 11.  Need to upgrade 12.1 RAC database to 12.2.
0
I am used to php/mysql where I would just join tables but mongoose seems to be a whole other beast.

I have a product schema and a user schema.

here is product:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const productSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    category: {
        type: String,
        required: true
    },
    image: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    userId: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    address: {
        city: {type: String, required: true }
    },
    createdAt: {
        type: Date,
        default: Date.now
    },
});

module.exports = mongoose.model('Product', productSchema);

Open in new window


And the user:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
    firstName: {
        type: String,
        required: true
    },
    lastName:  {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true,
        index: true,
        unique: true
    },
    contactNo: {
        type: String,
        required: true
    },
    password:  {
        type: String,
        required: true
    },
    address: {
        city: {type: String, required: true },
    }
});

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

Open in new window


When I as the admin user want to see the users first name and last name for the added product (as well as that product informatioN) I would to 'join' the 'tables' and based on the UserID in the product schema get the first name and last name from the users schema.

I am trying to use .populate here but not sure if it's correct or efficient.

exports.getApprove = (req, res, next) => {
    const productId = req.params.productId;
    Product.findById(productId)
    .populate('userId', 'firstName', 'lastName')
    .then(product => {
        res.render('account/approve', {
            pageTitle: 'Approve Listing',
            path: '/accounts/approve',
            product: product
        });
    })
    .catch(err => {
        console.log(err);
    });
};

Open in new window


console.log(product.userId.firstName);

Open in new window


Just wondering if I am not meant to use .exec() or .execPopulate() here
0
How do you make your npm package which includes an index.html page and a few folders of css and and javascript files launch a web page after you type "npm start" in the console window?
0
I'm going through a Udemy course on the MERN stack. Totally new territory for me and I've come across something that doesn't throw an error, but it's different from what should be on my screen according to the course.

Here's my code in my server.js file:

const express = require("express");

const app = express();

app.get("/", (req, res) => res.send("Hello"));

const port = process.env.PORT || 5000;

app.listen(port, () => console.log("Server running on port ${port}"));

Open in new window


When I do this on GIT Bash terminal:

$ node server

I get this in response:

Server running on port ${port}

According to the course, I should be getting:

Server running on port 5000.

There are no errors and if I go out to localhost:5000, I see "Hello," but the fact that I'm getting "{port}" instead of "5000" bothers me.

What am I missing?
1
When a user logs in I create a user object and store it in a session variable. However it is also storing the hashed password in the session but I would rather not do that. Is there a way to just remove the password from the session or would I have to create a seperate session variable for everything I wanted to store in a session? eg:

    User.findOne({email: email})
    .then(user => {
        if (!user) {
            return res.status(422).render('auth/login', {
                path: '/login', 
                pageTitle: 'Login', 
                errorMessage: 'Invalid login details', 
                email: email
            });
        }
        bcrypt.compare(password, user.password)
        .then(doMatch => {
            if (doMatch) {
                req.session.isLoggedIn = true;
                 req.session.user = user
                 return req.session.save((err) => {
                    res.redirect('/dashboard');
                }); 
            }

Open in new window


So instead of req.session.user = user maybe I would have to do:

req.session.user.email = user.email
req.session.user.firstName = user.firstName

Open in new window


And so on. I did try this but the password still remains in the session:

req.session.user = { ...user }
delete req.session.user.password

Open in new window

1
I am creating a session when a user logs in using express-session. I have however heard that the session should be stored in a database instead of in memory by means of something like connect-mongodb-session.

Is this accurate?
1
What is the best/easiest way to set your timezone in node js.

I found this on google but apparently it isn't totally reliable:

env TZ='Europe/Amsterdam' node server.js

Open in new window

1
I have only worked with php and mysql so am used to normalising my database and doing a lot of table joins etc. but I am moving over to node.js now and using mongoose with mongo DB and what I have gathered is that you shouldn't structure your db in the same way you would using php mysql. Apparently you should rather have a denormalised database. Could anyone give me an idea of where I could find a good example of this or possibly explain this in terms of an example? I have attached an image of a relational database setup I found on google and just wondered how the mongo db database would differ?
relational.png
0
High-tech healthcare
High-tech healthcare

From AI to wearables, telehealth to genomics to 3D printing — healthcare technology is seeing rapid advancement. Experts believe that this technological advancement will save money and save lives. Healthcare is changing dramatically, and emerging technology drives that change.

I'm a IT / Music Composition double major.

At school we use PHP a lot.

I want to start learning Node.js and express, at least the basics to get familiar with it.

The operating system I run on my laptop is Ubuntu 18.04.

How can I run both Node and PHP on my laptop?

------
0
Hi all I am using the treeview click event , in order to get the current node with TreeView1.GetNodeAt
I need the mouse click x,y location
probelm is the treeview click event wont fire when I add code to the mouse down event.
what am i doing wrong ...
1
I am trying to set up an express website.

I am getting data from a database in date formats, ie :    2018-11-21T00:00:00.000Z,

My database just default the time to 0000Z, but the day should be 11/21/2018

Whenever I try to display the date,
even as a simple ejs write: <%=item.date %>
it's automatically converting it to my timezone MST, and I'm getting the date as
Tue Nov 20 2018 17:00:00 GMT-0700 (Mountain Standard Time)

How can I set up a standard across my app to keep it as the same day of the month ?
0
How get the last document inserted in mongoDB

Im using nodejs, express mongoose
0
Hi, I am unable to extract the mac id info from the attached picture

var obj = msg.payload;
var json = JSON.parse(obj);


var MAC = json[0][1].mac;

msg.payload = MAC;

return msg;

Open in new window


mac.png
0
Hello Experts,

Need to calculate the average of the row in Node.JS to be stored in the Average Data

So far I have attempted to do the following after the first row.week1 data-field

+(row.week1+row.week2+row.week3+row.week4)/4

I have removed this line in the code as it has caused the script to break.

Here is the code:
//Following is basic configuration for Node.JS
var express = require('express');
var app = express();
var mysql= require('mysql');
//Line 6 createsthe connection between the mysql database. 
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '-------',
  database : 'databasetable'
});
//Getsthe information from either .html or node.js file. 
//Standard configuration
app.get('/', function (req,res) {
  connection.query('select * from storebenefit', function (error, results, fields){
    if (error) throw error;
	var reply='';
	//Object.keys() method returns an array of a given object's own property name
	//Callback to reply. access rows using index and columns using dot operator. 
	 reply+="<h2><table border='1'><tr>"
	 reply+="<td>No</td>"
	 reply+="<td>StoreName</td>"
	reply+="<td>Week1</td>"
	reply+="<td>Week2</td>"
	reply+="<td>Week3</td>"
	reply+="<td>Week4</td>"
	reply+="<td>Average</td></tr>"
	Object.keys(results).forEach(function(key){
		//For each loop passing results variable through the Object.Keys method.
		//Header of Table		
		var row= results[key];
		

Open in new window

0

Node.js

168

Solutions

302

Contributors

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Top Experts In
Node.js
<
Monthly
>