We help IT Professionals succeed at work.

Node.js

307

Solutions

382

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.

Here's the ticket I'm working on:

When the Prospects service queries for contacts, if values are undefined, the defaults are hardcoded and caught later on.

I.e in the backend:
phone number -> 000-000-0000
name -> . //Not kidding, it's literally a period
email -> noemail@email.com

Then in the front end, it checks for each of these hardcoded values before converting them to booleans. This seems very loose and confusing.

Basically, what's happening is if a user adds a contact to the database and they enter very little info (no email, no name or no phone number), the database will interpret those NULL values, in whatever combination they may be, and replace those NULLs with either a period, or what you see above.

The team member who's identified this anomaly is an exceptional programmer and I'm not cynical at all. My question: What would be the better approach?

I've got three fields available to me. The only required field is the, "name" - although I'm thinking that could also be left blank in light of there being the "period" accommodation mentioned above.

I've asked about making all three fields required and that was nixed.

So, what then, is the better approach to handling NULL values in this scenario?

Right now, rather than inserting a NULL value, things like "noemail@email.com" are being inserted instead. And then the system looks for "noemail@email.com" to determine whether or not there's a legitimate email address in the database.

It's a …
0
Here's a screenshot of the page I'm working on:

screenshot of app
The field in the red box is what's got me baffled.

My task is to change the formatting of the "02/26/2020 - 03/26/2020" that's in there right now to "Last 30 Days."

The app is using "DateRangePicker..."

Here's the relevant portion of the twig file:

<div class="row">
    <div class="col">
        <div class="card">
            <div class="card-header">
                <form class="filter-form form-inline view-report inline-filters" action="/reporting" method="post">
                    <div class="form-group">
                        <input type="text" name="date-range" id="date-range" placeholder="Date Range" class="form-control"/>
                    </div>
                    <div class="form-group">
                        <select name="user" placeholder="Seller" class="form-control user-select "></select>
                    </div>
                    <div class="form-group">
                        <button type="submit" class="btn btn-md btn-success"><i class="fa fa-check fa-lg"></i> View Report</button>
                    </div>
                    <div class="form-group">
                        <button type="button" class="btn btn-md btn-primary btn-print"><i class="fa fa-print fa-lg"></i> Print</button>
                        <button type="button" class="btn btn-md btn-primary btn-pdf"><i class="fa fa-file-pdf fa-lg"></i> PDF</button>
                    </div>
           

Open in new window

0
I'm working on an app that's using DateRangePicker...

There's been more than one third party contractor involved and I say that because of the way the formatting changes from page to page. My task is to institute some uniformity and I'm stuck.

Here's the dilemma:

The Dashboard:DateRangePicker

screenshot of dashboard
The twig file that goes along the Dashboard looks like this (this is just the relevant part):

 <div class="row filter-widget">
                <div class="col"><h4>Most Active</h4></div>
                <div class="col right-padding">
                    <form class="form-inline float-right" action="/dashboard/activitychart" data-chart-target="activityChart">                       
                        <div style="cursor: pointer;" class="form-control text-muted date-range" data-saved="{{dashboard_settings.most_active.range}}" onclick="dateRangeSelect('index3')">
                            <div style="margin-top: 3px;">
                                <i class="fa fa-calendar"></i>&nbsp;
                                <span style="padding-right: 30px;"></span> <i class="fa fa-caret-down"></i>
                            </div>                
                        </div>
                        <input type="text" style="display:none;"  placeholder="Date Range" name="date" required />

Open in new window


There's a JS file that goes along with this page. I have it here in its entirety ,but I'm looking at line #34.


Open in new window

0
I've been asked to edit an existing app by eliminating the "pagination" feature of a third party vendor called "Datatables."

Here's what the page looks like currently:

screenshot
Sweet little package, but the "features" that I have identified with an arrow within the big, black box - those are the guys that I'm needing to eliminate, but only in the event that the number of total rows is 10 or less.

My question is, "How?"

I've read through some documentation, but I'm at a point where I would welcome anyone who's been down this road before to give me some insight.

What do you think?

Thanks!
0
Here's a screenshot of my page:

leaflet.js
Here's what you're looking at:

This particular company doesn't have any address information .Within the code, there's a piece that's looking for some relevant data based on the postal code. If that info doesn't exist, the page will just sit there until it finally times out leaving the user confused and bewildered.

To solve that dilemma, once I found the relevant syntax, I just qualified things by engaging that query only if there were some postal codes to query.

So, now for the first time in days, I'm actually able to look at some data on the page that, beforehand was simply timing out with no real explanation, at least as far as the user was concerned.

However...

As you can tell by the screenshot, while the page is firing, beneath the hood there's an error message that references "leaflet.js."

Upon closer inspection, "heatmap.js" is involved as well.

So, here's my dilemma...

Although there's only one row in my database at this point, there will most certainly be multiple rows, most of which will represent a complete array of information. In other words, they will have some postal codes.

But in those instances where you've got a renegade row with no postal codes, I want to prevent "heatmap" from firing.

Here's the twig file:

<table id="main-dt" class="table custom make-datatable table-bordered table-striped dataTable no-footer" data-route="/companies/datatable" 

Open in new window

0
I saw these 2 libraries online:

ExcelJS
https://github.com/exceljs/exceljs

SheetJS js-xlsx
https://github.com/sheetjs/sheetjs

Just wondering which one is better in aspects such as stability, sustainability and resource consuming?

Thanks
0
EE Ninjas!

We are poised on the threshold of great things, I just know it!

I'm working on a ticket that involves some pagination, but I have yet to be able to retrieve the list of "companies" that will utilize the pagination...

So, I've got to fix / understand a problem before I can fix the problem.

The good news is that I've been able to decipher where the error is coming from but I'm not sure what it means or how to fix it.

Given the fact that I'm still a pig on roller skates when it comes to NodeJs, I'm certain there's someone out there who can look at the error and know exactly what to do.

First of all, here's the code. This is "companies.js" and it's coming from the "services" directory.

datatable(input, baseFilters = {}) {
        return new Promise((resolve, reject) => {
            let config = this._getDataTablesFilters(input);
            let pipeline = [];
            let countPipeline = []; // the filters used for counts

            // add in the base filters
            config.filters = Util.merge(baseFilters, config.filters);

            // set the base pipeline where/match clause
            pipeline.push({ $match: this._enforceScope() });

            // add sorting
            if (Object.keys(config.sort).length > 0) {
                if (typeof config.sort[0] == 'undefined') {
                    pipeline.push({ $sort: config.sort });
                }

            }
            // Owner
            pipeline.push(
               

Open in new window

0
Here's my attempt to troubleshoot a problem that I have yet to completely track down...

But I'm getting closer!

  if(typeof json !=='undefined') {
				  console.log("you've got some JSON");
				  console.log(json);
				  console.log(json.chartData);
				  if (json.chartData) {
					  buildChart(json.chartData);
				  }    
			  }
			  else {
				  console.log("no json data");
			  }

Open in new window


This is what I get back:

you've got some JSON
null

So, I've got some JSON, but when I try to see it, I get NULL.

I'm thinking I need a better IF statement, but how?

How do I check for both "undefined" and NULL?

I tried this and it didn't work:  if(typeof json !=='undefined' || json !== NULL) {
0
Here's what my page looks like right now:

screen shot of the ball of snot
The "Processing..." thing is coming from a JS file that I was able to track down. It's location looks like this:

companies.html.twig -> {% include 'partials/includes/datatables-js.html.twig' %} -> <script src="/assets/js/vendor/datatables/datatables.net/js/jquery.dataTables.min.js"></script>

The "database" dynamic is a third party vendor: https://datatables.net/. From what I can gather, the "Processing" thing is a generic graphic / text to indicate the database is chewing on something. Here's the file:

/*!
 DataTables 1.10.15
 ©2008-2017 SpryMedia Ltd - datatables.net/license
*/
(function(h){"function"===typeof define&&define.amd?define(["jquery"],function(E){return h(E,window,document)}):"object"===typeof exports?module.exports=function(E,H){E||(E=window);H||(H="undefined"!==typeof window?require("jquery"):require("jquery")(E));return h(H,E,E.document)}:h(jQuery,window,document)})(function(h,E,H,k){function Y(a){var b,c,d={};h.each(a,function(e){if((b=e.match(/^([^A-Z]+?)([A-Z])/))&&-1!=="a aa ai ao as b fn i m o s ".indexOf(b[1]+" "))c=e.replace(b[0],b[2].toLowerCase()),
d[c]=e,"o"===b[1]&&Y(a[e])});a._hungarianMap=d}function J(a,b,c){a._hungarianMap||Y(a);var d;h.each(b,function(e){d=a._hungarianMap[e];if(d!==k&&(c||b[d]===k))"o"===d.charAt(0)?(b[d]||(b[d]={}),h.extend(!0,b[d],b[e]),J(a[d],b[d],c)):b[d]=b[e]})}function Fa(a){var 

Open in new window

0
Here's a screenshot of the page I'm working on:

screenshot of the app
The thing that I'm targeting is what you see in the big, black box - "An unexpected error was encountered while trying to process your request. Please try again."

That message is being generated as a result of the "submit" function you see on "profile.js" -  this is a stripped down version...

router.post('/profile/save', async (req, res) => {
  try {
    if (typeof req.body.user == 'undefined') {
      return res.send(user.error('Invalid request.'));
      }
    	
	//checking to ensure current password matches what's in the database before updating profile information
	let check = await(user.getOne(global._user._id));

	let the_password=check.password;
	let the_current_password = req.body.current_password;
	let quiz = await(user.confirmPassword(the_current_password, the_password));
	if(quiz=="yes") {
		console.log("book");
                //here's where my update / save functionality will occur
	}
	else {
		//what do I need to do here?
	}

  } catch (err) {
    res.status(500).send(user.error());
  }

});

Open in new window


"profile.html.twig" is the page the user is actually engaging in order to alter their password etc. It references "profile.js" (the code that you see above" as well as "user-form.js." "user-form.js" is being used to validate the form data as well as produce the "An unexpected error was encountered while trying to process your request. Please try again." error if something goes south with the "save / update" functionality - at least that's what I'm thinking.

Here's my dilemma.

I want to change the text in the message that you see in the screenshot above to "Be sure the password you've entered in the "Confirm Password" field matches what's in the database."

How?

It would see that "user-form.js" is convinced that there's an error that justifies the "An unexpected error..." message.

Why?

I don't understand why on "profile.js" the code is allowed to proceed to the point where I'm sending the "user-form.js" file a 500 status.

Secondly, what changes do I have to make in order to alter the "An unexpected error..." text to "Your 'confirm password' entry doesn't match what's in the database."?

Thanks!
0
I've got a form that looks like this:

<form id="user-form" class="needs-validation" method="post" action="/profile/save" novalidate>

...

      <div class="password-wrapper">
        <button type="button" class="btn btn-primary btn-change-password"><i class="fas fa-fw fa-key"></i> Change Password</button>
        <div class="password-template d-none">
			<div class="row">
				<div class="col-lg-12">
				To change your password, begin by entering your current password first...<br><br>
					<div class="md-form">
						<input type="password" id="current-password" name="current_password" class="form-control" value="">
						<label for="current_password"><a id="expose-current" href="#" style="cursor:text;" tabindex="-1">Current Password</a></label>
					</div>
				</div>
			</div>
			<!-- new row -->
			<div class="row">
				<div class="col-lg-6" style="margin-top:-25px;">
					<div class="md-form">              
						<input type="password" id="user-password" name="user[password]" class="form-control" required />
						<label for="user-password"><a id="exposure" href="#" style="cursor:text;" tabindex="-1">Password*</a></label>
					</div>
				</div>
				<div class="col-lg-6" style="margin-top:-25px;">
					<div class="md-form">
						<input type="password" id="user-confirm" class="form-control" required />
						<label for="user-password">Confirm*</label>
					</div>
				</div>
			</div>
			<div class="row">
				<div class="col-lg-12">
					<div style="font-size:9pt; 

Open in new window

0
I'm new to Nodejs and I'm working on a ticket where I'm being tasked with first checking the user's current password before they're allowed to change it.

Here's the current route:

router.post('/profile/save', async (req, res) => {
  try {
    if (typeof req.body.user == 'undefined') {
      return res.send(user.error('Invalid request.'));
      }
          
      //checking to ensure current password matches what's in the database before updating profile information
      
      let check = await(user.getOne(global._user._id // here's where I get stuck
      
    let resp = await user.save(global._user._id, req.body.user);
    if (resp.error) {
      return res.send(resp);
    }

  #1) let data = await user.getOne( global._user._id, [
      { path: 'account', model: 'Account'}
    ] );

    req.session.user = Object.assign({}, req.session.user, data);

    flash.add(req, 'Your profile has been successfully saved.', 'success');

    res.send(resp);
  } catch (err) {
    res.status(500).send(User.error());
  }
});

You can see where I've notated "here's where I get stuck," but I've got an idea of what the flow needs to look like.

I need to first find the row that coincides with the global user_id. After I get that array, I need to parse it out and decrypt the password as it exists in the database and compare that to what the user entered in the "current password" field.

One other thing: #1 - what is user.getOne? I've seen "findOne," but can't …
0
I'm working on a ticket whose title is, "Redirect from form is not validated."

Not sure what that means.

Here's what I know:
The app is using "express-session"
I'm storing the session data in "user-sessions"

try {
  let sessionObj = session({
    secret: process.env.SESSION_SECRET,
    store: new MongoStore({
      mongooseConnection: global.db,
      collection: 'user_sessions'
    }),
    cookie: {
      maxAge: (60 * 60) * 1000, // 1 hour - milliseconds
    },
    rolling: true, // resets the cookie max age on each request
    resave: false,
    saveUninitialized: true
  });

  app.use(sessionObj);
} catch (err) {
  console.log('Error: ', err);
  return false;
}

Open in new window

After successfully logging in, I can do a "console.log(req.session);" and see all of my session data.

Here's the file coming out of my "services..."

  async auth(email, password) {
    const isDev = (process.env.ENV == 'local' || process.env.ENV == 'dev');
    let match = {
      email: email,
      active: true
    };

    try {
        let user = await this.loadUser(match);        
      // validate the password hash
      if (!isDev) {
        await this.checkPasswordHash(password, user.password);
      }

      return this.success(user);
    } catch (err) {
      console.log('Error: ', err);
      return this.error(err);
    }
  }

Open in new window


And here's the login route:

router.post('/login/auth', async (req, res) => {
  if (typeof req.body.email == 'undefined' || typeof req.body.password == 'undefined') {
    flash.add(req, 'Please enter a valid email address and password before trying again.', 'danger');
    return res.redirect('/login');
  }

  let resp = await user.auth(req.body.email, req.body.password);

  if (resp.error) {
    flash.add(req, 'The provided email address and password combination is invalid. Please try again. If you need further assistance, please call 855.581.9910.', 'danger');
    return res.redirect('/login');
  }

  req.session.user = resp.data;
    await user.lastLogin();//Update lastLogin date
  let redirect = (req.body.redirect != '') ? req.body.redirect : '/';

  res.redirect(redirect);
});

Open in new window


This may all be golden and I just don't know it. But before I go asking around, I wanted to do my due diligence and make sure that I wasn't missing something.

Does this look OK? If something is jacked up, what's lacking and how can I fix it?
0
I'm getting this error and I don't know how to fix it.

I'm using GraphQL with a React front end. Everything is looking good, but on the back end I'm getting this:

C:\wamp64\www\adm\node\api\node_modules\graphql\validation\validate.js:108
    throw new Error(errors.map(function (error) {
    ^

Error: There can be only one type named "RootQuery".
    at assertValidSDL (C:\wamp64\www\adm\node\api\node_modules\graphql\validation\validate.js:108:11)
    at buildASTSchema (C:\wamp64\www\adm\node\api\node_modules\graphql\utilities\buildASTSchema.js:71:34)
    at buildSchema (C:\wamp64\www\adm\node\api\node_modules\graphql\utilities\buildASTSchema.js:462:10)
    at Object.<anonymous> (C:\wamp64\www\adm\node\api\graphql\schema.js:3:18)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (C:\wamp64\www\adm\node\api\app.js:9:23)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at 

Open in new window

0
I've gotten spoiled using Nodemon and while I've got that installed on the app that I'm working on (I didn't build it, I'm just working on it), it doesn't restart the server in the way I'm accustomed to and I don't know why.

Here's the way things look on my Command Line:

b.gust@AHA-DT-BGUST2 MINGW64 /c/wamp64/www/bsmart (BRUCE-code-cleanup)
$ npm start

> cams@1.0.0 start C:\wamp64\www\bsmart
> nodemon index.js

[nodemon] 2.0.2
[nodemon] to restart at any time, enter `rs`
[nodemon] watching dir(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Listening on PORT: 3000

Open in new window


...and here are my scripts:

{
  "name": "cams",
  "version": "1.0.0",
  "description": "Client Acquisition Management System",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
	"start": "nodemon index.js"
  },
  "author": "Mitch Cannon",
  "dependencies": {
    "aws-sdk": "^2.382.0",
    "bcrypt": "^3.0.2",
    "body-parser": "^1.18.3",
    "connect-mongo": "^2.0.3",
    "csv-stream": "^0.2.0",
    "dotenv": "^6.2.0",
    "express": "^4.16.4",
    "express-fileupload": "^1.0.0",
    "express-session": "^1.15.6",
    "express-sessions": "^1.0.6",
    "js-md5": "^0.7.3",
    "jsonwebtoken": "^8.4.0",
    "lodash": "^4.17.10",
    "moment": "^2.23.0",
    "moment-timezone": "^0.5.23",
    "mongodb": "^3.1.10",
    "mongoose": "^5.4.0",
    "multer-s3": "^2.9.0",
    "node-utils": "",
    "nodemailer": "^6.2.1",
    "nodemon": "^2.0.2",
    "papaparse": "^4.6.2",
    "request": "^2.88.0",
    "socket.io": "^2.2.0",
    "twig": "^1.12.0",
    "unzipper": "^0.9.11",
    "uuid": "^3.3.2",
    "validator": "^10.10.0"
  }
}

Open in new window


What am I missing that would allow for Nodemon to operate in the way I'm accustomed, as far as me making a change in the code and the server automatically restarting?
0
I'm working on a Nodejs application and I want to give the user the opportunity to view the password they're attempting to set.

I've seen this option before where you can click on an "eye" icon and you can see the characters that would otherwise be represented by asterisks.

How do you pull that off?
0
Here's the code that's getting triggered by the "user-form-show" method:

$(window).on('user-form-show', function(e, userId, opts){
    // prep the modal
    $uModal.find('.loading').show();
    $uModal.find('.main').hide();

    // show the modal loading screen
    $.magnificPopup.open({
      alignTop: true,
      items: {
        src: $uModal, // can be a HTML string, jQuery object, or CSS selector
        type: 'inline'
      }
    });

    // clear the cached data
    data = {};

    // clear the form from any previous data
    clearForm();
           

    // load the data if a valid id is provided
    if (typeof userId != 'undefined' && userId != 'new') {
      loadFormData(userId);
    } else {
      // set the id for a new user
        loadedUserId = 'new';
        // load drag & drop members 
        teamDragula(userId);

        $form.find('#user-role').attr('data-user-id', loadedUserId);
      // force the password fields
      $form.find('.btn-change-password').replaceWith( $passwordForm.clone() );
      $form.find('.btn-cancel-password').closest('.col').remove();

      // show the form
      $uModal.find('.loading').hide();
      $uModal.find('.main').show();
    }
  });

Open in new window


The line that I'm wanting to understand is this:

$form.find('#user-role').attr('data-user-id', loadedUserId);

Earlier in the file, $uModal was defined like this:

var $uModal = $('#modal-user-form'),
      $form = $('#user-form'),
      $passwordButton = $form.find('.btn-change-password').clone(),
      $passwordForm = $form.find('.password-template').clone().removeClass('d-none'),
      data = [],
      loadedUserId = '',
      passwordRegex = {
        upper: /[A-Z]{1,}/,
        lower: /[a-z]{1,}/,
        number: /[0-9]{1,}/,
        special: /[\!\@\#\$\%\^\&\*]{1,}/,
        total: /.{8,}/
      };

Open in new window


When you follow the trail as far as the "user-form.html.twig," you find that the portion of code that I've got in bold is referring to this:

<select id="user-role" name="user[role]" class="form-control mdb-select md-form" required>
               {% if roles is not empty %}
                {% for role in roles %}                
                    <option value="{{role}}" {{role=='Sales Representative'?'selected="selected"':''}} >{{role}}</option>
                {% endfor %}
                {% endif %}
            </select>


My question is: Where is "data-user-id?"

I'm thinking that the referenced SELECT would have a "user-id" value attached to is and the ".attr('data-user-id', loadedUserId" code is populating that value with the "loadedUserId" value, yes?

What is "att('data-user-id', loaded.UserId)" doing?
0
Here's my code:

$(window).on('user-form-show', function(e, userId, opts){
    // prep the modal
    $uModal.find('.loading').show();
    $uModal.find('.main').hide();

    // show the modal loading screen
    $.magnificPopup.open({
      alignTop: true,
      items: {
        src: $uModal, // can be a HTML string, jQuery object, or CSS selector
        type: 'inline'
      }
    });

    // clear the cached data
    data = {};

    // clear the form from any previous data
    clearForm();
           

    // load the data if a valid id is provided
    if (typeof userId != 'undefined' && userId != 'new') {
      loadFormData(userId);
    } else {
      // set the id for a new user
        loadedUserId = 'new';
        // load drag & drop members 
        teamDragula(userId);

        $form.find('#user-role').attr('data-user-id', loadedUserId);
      // force the password fields
      $form.find('.btn-change-password').replaceWith( $passwordForm.clone() );
      $form.find('.btn-cancel-password').closest('.col').remove();

      // show the form
      $uModal.find('.loading').hide();
      $uModal.find('.main').show();
    }
  });

Open in new window


My question is this:

In the first line, you have this:

  $(window).on('user-form-show', function(e, userId, opts){

How needful is the "e" character?

From what I can gather, under the hood in every Event Handler, the "event object" is being passed into the function as an argument. I've seen this a lot with "event.preventDefault."

Thing is, how necessary is it? The reason I ask is because you don't see "e" all the time, and yet it seems like it's always there in the background even it if's not being coded as such.

Is that correct?

Is the event object (e) always assumed even if it's not being included as part of the syntax?

Could I just as easily write the above code as $(window).on('user-form-show', function(userId, opts)?

Thanks!
0
Here's the code that I'm working on:

async auth(email, password) {
   1) const isDev = (process.env.ENV == 'local' || process.env.ENV == 'dev');
	//console.log(email);
    2) let match = {
      email: email,
      active: true
    };

    try {
        3) let user = await this.loadUser(match);        
      // validate the password hash
      if (!isDev) {
        await this.checkPasswordHash(password, user.password);
      }

      return this.success(user);
    } catch (err) {
      console.log('Error: ', err);
      return this.error(err);
    }
  }

Open in new window


Here are my questions / explanations. Could you please either "proof" or answer my quandaries?

1 I've not seen this before: const isDev = (process.env.ENV == 'local' || process.env.ENV == 'dev');

I'm assuming it's something similar to a ternary IF statement, but what does it mean? And I'm just shooting from my hip as far as it being a ternary IF statement. Generally, when faced with this kind of thing, I'll refer to https://davidwalsh.name/php-ternary-examples, but this genuinely baffles me.

2 "match" is a variable that houses an array consisting of two key / value pairs: "email" and "active." "email" is one of the arguments being passed into the method, so that's going to be coming from the login page.

3 loadUser looks like this:

  loadUser(match={}) {
    return new Promise( async (resolve, reject) => {
      this.model.aggregate([
        {$match: match},
       

Open in new window

0
This works:

<script>

$(document).ready(function() {
	
	const fetchData = () => {
	  const promise = new Promise((resolve, reject) => {
		setTimeout(() => {
		  resolve("Loose Cannon Fitness");
		}, 100);
	  });
	  return promise;
	};
	
	
	setTimeout( async () => {
	  console.log("Smith and Gone");
	  var text = await fetchData();
	  console.log(text);
	}, 200);


});

</script>

Open in new window


What I'm attempting to do is get a better understanding of Callbacks, Promises and Async / Await(s).

To do that, I started with a very basic example and just built on that - adding / editing things in order to match what represented the new paradigm.

Here's the basic Callback:

$(document).ready(function() {
	
	x = function(cb) {
		setTimeout(function() {
			console.log("Smith and Gone");
			cb();
		}, 200);
	}

	y = function() {
		console.log("Loose Cannon Fitness");
	}
	
	x(y);
	
});

Open in new window


Here's the same result structured using ES6:

$(document).ready(function() {
	
	x = (cb) => {
		setTimeout(function() {
			console.log("Smith and Gone");
			cb();
		}, 200);
	}

	let y = () => {
		console.log("Loose Cannon Fitness");
	}
	
	x(y);
	
});

Open in new window


Here it is written using Promises:

const fetchData = () => {
  const promise = new Promise((resolve, reject) => {
	setTimeout(() => {
	  resolve("Loose Cannon Fitness");
	}, 100);
  });
  return promise;
};

setTimeout(() => {
  console.log("Smith and Gone");
  fetchData()
  .then(text => {
	console.log(text);
  });
}, 200);

Open in new window


And here it is written using an Async / Await dynamic:

$(document).ready(function() {
	
	const fetchData = () => {
	  const promise = new Promise((resolve, reject) => {
		setTimeout(() => {
		  resolve("Loose Cannon Fitness");
		}, 100);
	  });
	  return promise;
	};
	
	setTimeout( async () => {
	  console.log("Smith and Gone");
	  var text = await fetchData();
	  console.log(text);
	}, 200);

});

Open in new window


Just for the sake of drill, I did this:

$(document).ready(function() {
		
	const fetchData = () => {
		setTimeout(function() {
			console.log("Loose Cannon Fitness");
		}, 200);
	}

       setTimeout( async () => {
       console.log("Smith and Gone");
       var text = await fetchData();
       console.log(text);
      }, 200);
 
});

Open in new window


What I wanted to do was make "fetchData" a regular ES6 function as opposed to something that was incorporating a Promise.

The result was an error that looked like this:

Smith and Gone
stunt.php:54 undefined
stunt.php:25 Loose Cannon Fitness


Line #54 was "console.log(text)."

I'm assuming that "undefined" is a result of the fact that "await" is expecting a Promise.

Is that correct?

That said, is there a way to do what I've got written above where my "setTimeout" function works as it "awaits" fetchData written as an anonymous funtion?

This isn't something I would use in a practical setting. Rather, it's something I'm putting together for my own edification

What do you think?

In an effort to figure it out for myself, I tried this:

	const fetchData = () => {
		setTimeout(function() {
			//console.log("Loose Cannon Fitness");
			//var text = "Loose Cannon Fitness";
			//return text;
			return "Loose Cannon Fitness";
		}, 200);
	}

Open in new window


That didn't work.

I tried this:


Open in new window

0
Here's my Promise:

$(document).ready(function() {
	
	const fetchData = () => {
	  const promise = new Promise((resolve, reject) => {
		setTimeout(() => {
		  resolve("Loose Cannon Fitness");
		}, 100);
	  });
	  return promise;
	};

	setTimeout(() => {
	  console.log("Smith and Gone");
	  fetchData()
	  .then(text => {
		console.log(text);
	  });
	}, 200);

});

Open in new window


How would I convert that to an "async / await" dynamic?
0
Need to install Node.js on my Windows 10 .NET Development machine

I need to install Node so I can install jsinspect so I can find code duplication that got there through heavy us of copy-paste.

I have worked with Node in the past. But, I want to be 100% sure I am not going to in any way harm my Windows PC, since that is my bread-and-butter machine.

Can you provide me the safest set of steps to do this?

Thanks
0
hi am having error running my nodejs








PS C:\Angular3\mean-course> node server.js
C:\Angular3\mean-course\server.js:47
app.set("port", port);
    ^

TypeError: app.set is not a function
    at Object.<anonymous> (C:\Angular3\mean-course\server.js:47:5)
    at Module._compile (internal/modules/cjs/loader.js:778:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
PS C:\Angular3\mean-course> npm install
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\webpack-dev-server\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules\watchpack\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.1.2
0
Here's my initial code:

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    'Access-Control-Allow-Methods',
    'GET, POST, PUT, PATCH, DELETE'
  );
  res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
  next();
});

Open in new window


This is part of a Node.js tutorial I'm going through. It's a React front end that interacts with an API which utilizes GraphQL.

The code that I've got above is from the "app.js" file that's a part of the API. I've got the code in its entirety below:

const path = require("path");

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const multer = require("multer");
const graphqlHttp = require('express-graphql');

const graphqlSchema = require('./graphql/schema');
const graphqlResolver = require('./graphql/resolvers');

const app = express();

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    //cb(null, uuidv4());
    cb(null, 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(bodyParser.json());
app.use(
  multer({
    storage: fileStorage,
    fileFilter: fileFilter
  }).single("image")
);

Open in new window

0
Im noob in node.js and my clients program is generating a build file from the code. But i dont know how this works! Im in a crunch for time on the clock. Can someone explain how this is being generated?  The program works off the generated Build File and not my code. Thank you.

Node.js build file auto generated.
0

Node.js

307

Solutions

382

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.