Node.js

152

Solutions

287

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

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
Big Business Goals? Which KPIs Will Help You
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

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
Somebody has a good example autocomplete search nodejs, express, mongodb
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
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 have a problem in my project probably with babel-cli or other module related with babel because it shoots this error when I use only ES5 :
TypeError: Class constructor model cannot be invoked without 'new'
so the error occurred when I use this command to create models with sequelize , in this line :
var model = db.sequelize.import(path.join(__dirname,"models/", file));

Open in new window

this is the whole code of connect.js file :
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = 'development';
const config = require('../config/config')[env];

const sequelize  = new Sequelize(config.database.database_name, config.database.username, config.database.password, config.database.database_config);

var db = {
    sequelize : sequelize,
    Sequelize : Sequelize
};

db.sequelize.authenticate().then(() => {
    console.log('database worked !!!');


    fs.readdirSync(path.join(__dirname,'models/')).filter(file => {
        return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
    }).forEach(file => {
        var model = db.sequelize.import(path.join(__dirname,"models/", file));
        //var model = require(path.join(__dirname,"models/", file))(sequelize, Sequelize);
        db[model.name] = model;
    });

    Object.keys(db).forEach(modelName => {
        if (db[modelName].associate) {
            db[modelName].associate(db);
  

Open in new window

0
So when I published an npm package, for some reason, it threw my profile name with my package information into the node_modules so here is what happens when it is installed...

-testdirectory
--node_modules folder
--package-lock.json
---node_modules/@myusername/myprojectname

this is completely the wrong project structure.  What I need is the following:

I need the following in the same folder
myprojectname folder
node_modules folder

but for some reason, the project folder gets pushed into node_modules.  What can i do to correct this?
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
Protecting & Securing Your Critical Data
LVL 1
Protecting & Securing Your Critical Data

Considering 93 percent of companies file for bankruptcy within 12 months of a disaster that blocked access to their data for 10 days or more, planning for the worst is just smart business. Learn how Acronis Backup integrates security at every stage

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
I am using a 3rd party script to upload images via Ajax and the callback gives you an array with the details of each uploaded image like the name, size, etc. I want to store the name of the images in the database.

I tried this but it only inserts the first image name:

        if (data.isSuccess) {
         const uploaded = uploader.getFileList();
         for (const images of uploaded) {
            console.log(images.name);
            const upload = new uploadModel({
                imgName: images.name
            });
            return upload.save();
         }

Open in new window


If I just console.log it however, it lists all the image names.
1
I have a form for adding a product which lets a user input product name, description etc. and also allows an image upload.

In my app.js file which is my entry point, I have:

const fileStorage = multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'uploads');
    },
    filename: (req, file, cb) => {
       cb(null, new Date().toISOString() + '-' + file.originalname);
    }
  });


  const fileFilter = (req, file, cb) => {
    if (
      file.mimetype === 'image/png' ||
      file.mimetype === 'image/jpg' ||
      file.mimetype === 'image/jpeg'
    ) {
      cb(null, true);
    } else {
      cb(null, false);
    }
  };

app.use(multer({ storage: fileStorage , fileFilter: fileFilter, limits: { fileSize: 100000} }).single('image'));

Open in new window


Here is my controller:

exports.postAddListing = (req, res, next) => {
    const title = req.body.title;
    const category = req.body.category;
    const description = req.body.description;
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(422).render('account/add-listing', {
            pageTitle: 'Add Item',
            path: '/account/add-listing',
            errorMessage: errors.array(),
            successMessage: null,
            oldInput: {
                title: title,
                description: description
            }
        });
    }

    const image = req.file;
    const imageUrl = image.path;

    const product = new Product({
        title: title,
        category: category,
        description: description,
        userId: req.user,
        datePosted: Date.now(),
        imageUrl: imageUrl
    });
    product.save()
    .then(result => {
        const successMessage = req.flash('success', 'Item sucessfully added');
        res.redirect('/account/add-listing');
    })
    .catch(err => console.log(err));
};

Open in new window


I am using express-validator for form validation. The problem I have is that if I for example leave all fields empty but choose an image, validation will fire and I will get error messages but the image will still upload. If form validation fails I don't want the image to upload but not sure how to achieve that.
0
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
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
Determine the Perfect Price for Your IT Services
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

I am just getting started with Angular (https://angular.io).

What I notice is every time I create a new project using the ng new myproject  (e.g. ng new angular-tour-of-heroes), it creates a (nodes_module) directory with like over 20,000 files.

I understand that in some cases you can set different settings that don't require all of the same nodes so that would create a different set of files for nodes_module.

But if I have multiple projects that all will use the same basic set of files, is there a way to share the nodes_module?

It seems that if I'm working on ten different projects at once that's an awful lot of files and disk space that is identical...

Is there a space saving option?

Also, if this is the best way to do this, is there a best practice for how to archive old projects.  In other words, if I have a project that I work on and turn over to a client, I no longer need it on my drive taking space. But if I want to save it in case the client wants me to replicate it again... is it okay just to save the src files or do I need to save the whole thing including the 24K+ nodes_miles?

Thanks.
0
There is a Java Spring MVC project and a requirement to delegate the frontend to an external team of frontend developers. The backend is secret (proprietary trading system) and the frontend is therefore the only part of it that can be disclosed (Freemarker templates with HTML + CSS, JS, images).

I figured node.js has a freemarker library and the express server. It can render Freemarker templates:

const express = require('express')
const fs = require('fs');
const app = express()
const port = 3000

const Freemarker = require('freemarker');	 
const freemarker = new Freemarker();

app.get('/', (req, res) => {
	var model = {
		title: 'Test render',
		test: 'freemarker in JS!'
	};	

	console.log("Opening /");
	fs.readFile('main.ftlh', 'utf8', function(err, contents) {
		freemarker.render(contents, model, (err, result) => {
		  if (err) {
			throw new Error(err);
		  }
		  		  
		  res.send(result);
		});
	});	
})

app.listen(port, () => { } /*console.log(`Example app listening on port ${port}!`)*/)

Open in new window


Is there any quick solution to create mock controllers? Mock controllers should have some hardcoded data in their model just to make it possible to render the views.
Ideally, they would be generated somehow from the original Java controllers. I know regular expressions may be able to do it, but is there perhaps a better way? Some tool?
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

Node.js

152

Solutions

287

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
>