[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Node.js

135

Solutions

265

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

How get the last document inserted in mongoDB

Im using nodejs, express mongoose
0
Check Out How Miercom Evaluates Wi-Fi Security!
Check Out How Miercom Evaluates Wi-Fi Security!

It's not just about Wi-Fi connectivity anymore. A wireless security breach can cost your business large amounts of time, trouble, and expense. Plus, hear first-hand from Miercom on how WatchGuard's Wi-Fi security stacks up against the competition plus a LIVE demo!

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
Hi Experts!

Got issue with Node.JS not running in the command line. Any suggestions for this issue so that the code is up and running? The password part is not issue but line 31 SyntaxError?

var express = require('express');
var app = express();
var mysql= require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '---------------------',
  database : 'nodeTest'
});
app.get('/', function (req,res) {
  connection.query('select * from test_table', function (error, results, fields) {
    if (error) throw error;
	var reply='';
	Object.keys(results).forEach(function(key){
		//For each loop passing results variable through the Object.Keys method. 
		var row= results[key];
		row+="<h2>"+row.id+":"+row.name+"</h2><br>";

  });
  	res.send(reply);
});
});
app.listen(3000, function () {
  console.log('Example app listening on port 3000!');
});

Open in new window

0
Dear All
    i would like to know the loading mechanism of Ali's egg module, any advice? thanks
0
Hi,

i am sending data to Mariadb and its works fine using Node RED. Its pop up error in idea situation where no data been send. While the code end in else conditions the error message pop up. May I know to over this error.
var status = context.get('status')||0;

var current = global.get("stdTime");
var daycurrent = global.get("stdDayTime");

var  m_work_start = global.get('Mor_Shift_Start');
var  m_work_end = global.get('Mor_Shift_Stop');

var n_work_start = global.get('Night_Shift_Start');
var n_work_end = global.get('Night_Shift_Stop');


/********************** Between Morning & Night Shift ********************************************/
//from night to morning
if (current > n_work_end && current < m_work_start) {
    if(status === 0)
        msg.topic ="INSERT INTO overalldata (deviceID, prdline, line, pulse, sumPulse, time, outputPin, STtarget, shiftTRGT, STActual, different, targetACHV, cycleTime, remarks) VALUES ('1', 'line 1', '1', '0', '0', '"+daycurrent+"', 'RESET', '0', '0', '0', '0', '0', '1', 'ok')";
        status = 1;
        context.set('status',status);
}

//from morning to night
else if (current < n_work_start && current > m_work_end) {
    if(status === 0)
        msg.topic ="INSERT INTO overalldata (deviceID, prdline, line, pulse, sumPulse, time, outputPin, STtarget, shiftTRGT, STActual, different, targetACHV, cycleTime, remarks) VALUES ('1', 'line 1', '1', '0', '0', '"+daycurrent+"', 'RESET', '0', '0', '0', '0', '0', '1', 'ok')";
        status = 

Open in new window

0
HI,

i am running a production application for night shift. Its start from 2000 hrs to 0800 hrs by defaults. Between this hours there are 4 breaks: -
2200 hrs ~ 2215 hrs
0005 hrs ~ 0035 hrs
0315 hrs ~ 0330 hrs
0530 hrs ~ 0550 hrs

This breaks are defaults setting where user can change the setting accordingly.

i have to calculate the production output only on production hours and system off automatically on breaks time. Base on default setting i am to determine my production hours as follows: -
 Break      start time ~ stop time ( i am comparing the current time between this running hours)
 1              2000 hrs  ~ 2200 hrs    (20:00:00 < current && current >22:00:00)
 2              2215 hrs  ~ 0005 hrs    (22:15:00 < current && current >00:00:00) || (00:00:00 < current && current >00:05:00)  
 3              0035 hrs  ~ 0315 hrs
 4              0330 hrs  ~ 0530 hrs
 5              0550 hrs  ~ 0800 hrs

I running in node red.

if (( current >= N_Prod_Start && current <= '23:59:59') || (current >= '00:00:00' && current <= N_Prod_Stop)){
    if ( current > N_Start[0] && current < N_Stop[0] ){
        for (i=0; i <= loop; i++){
            ST_cal(N_Start[0], current,cycle[i],0,i);
        }
    }
    else if (( current > N_Start[1] && current <= '23:59:59') || (current >= '00:00:00' && current < N_Stop[1] )){
        for (i=0; i < loop; i++){
            ST_cal(N_Start[1], current,N_cycle[i],N_sec[0],i);   
        } 
    }
    else if ( current 

Open in new window

0
Hi everyone
Can anyone help me or show me the right way to approach this assignment for my class? I am new to programming and missed lots of class. I just want to know the step by step process or the things I need to learn it.


Node-Express      Site      with      Nodemailer      – Research      Assignment
Using      a      brand      new      Express      Generator      App      skeleton,      add      the      following:
(1) Build      out      a      few      ‘standard’      routes (contact,      team,      etc.)      in      the      application;      
each      of      these      routes should      in      the      end      render      out      a      full      HTML-based      page
(from      included      partial files,      see      below),      but      you      do      not      need      any      content      
other      than      placeholder      text/image      content      in      each      view.
(2)Install      the      Nodemailer module      through      npm to      make      it      available locally,      
(using      SMTP) in      your      application.      Use      the      Nodemailer      documentation      as      a      
guide      and      build      a      route      and      a      view (form) to      enable      sending      an      email      through      
a      mail      service      (NOTE:      If      you      use      Gmail      you      may      get      a      warning      email      when      
you      test      it      that      your      Google      credentials      were      used      by      an      ‘unsafe’      app,      that      is      
to      be      expected). Search      for      Nodemailer      from      the      npm      main      site,      and      you      will      
get      to      the      documentation      that      will      show      you      how      to      set      everything      up.
(3) Use partials in      ejs,      the      page      renderer      you      are currently using,      so      that      you      can      
create      and      include      ‘proper’ views      (e.g.,      header,      footer).      Then      modify      all fullpage
ejs      examples into      a      more      modular      form.
(4) Add      some      CSS      styling to      the      ejs      template      views      in      your      application, again      not      
a      fully      designed      …
0
Experts!

I have created a Node.JS web app with two APis. One of the APIs is GUI where the end-user sees the GUI. The second API is the auth guard that will go and talk to 1L using OPENID > authenticate > fetch user profile and render information to the GUI for the end-user.

We originally wanted to use SAML assertion (SSO) similar to Zendesk or Others that when someone is authenticated to 1L and you navigate to the site domain.zendesk.com the established logged in token just redirects you to the site. When you are not logged in to 1L and you go to the site you are redirected to 1L for auth then redirected back to the site of choice once you successfully auth.

Our application does not have a user database, instead, we are banking on 1L to do authentication for us and also pass through user information to our second API so that we can then pass specific end-user details from the internal side to the GUI. The end goal is to be able to authenticate with 1L and be redirected to the sales.cbac.com and be able to know user specific details about the current user, but that user is to never have to access the login page

Right now, we had to spin up a login page that will accept user info > sends info to auth guard to call 1L auth > returns valid user and user profile info > all using OPENID.

What is the best approach? It seems like we are missing something.

API URL1 (GUI) - sales.cbac.com API URL2 (auth guards - OPENID) - sales-api.cbac.com Current state you land at …
0
Hello Experts

I have been able to previously install npm install express into individual folders earlier today but now can't.

If I attempt to install npm express into a targeted folder, it loads in the cmd line but does not generate the package and node_modules file and folder that it's suppose to in the targetted folder.

Is there a solution available for this? (no static file servers/request, only vanilla npm install express). I need to install the express module into any folder that is targetted/destination on a desktop.
0
IT Degree with Certifications Included
IT Degree with Certifications Included

Aspire to become a network administrator, network security analyst, or computer and information systems manager? Make the most of your experience as an IT professional by earning your B.S. in Network Operations and Security.

Hello Experts,

I am looking for a solution to a ER_NOT_SUPPORTED_AUTH_MODE that is stating that the authentication protocol is not supported requested by the server, consider upgrading.

The latest version of MYSQL out is 8.0.12 and has no updates to install. MySQL and Node.JS are being used in combination for this demonstration. The node.js file runs fine in the win cmd line when referencing the file.

There is a password that I have set to the MySQL server, which will be needed. This is a LocalHost. Running the page set at the port 3000 returns as a "unable to connect error"

I have tried this solution to no avail in the mySQL command line in an attempt to bridge the issue:

use mysql;
update user set authentication_string=password(''), plugin='mysql_native_password' where user='root';

Only the mySQL command line can be used (excluding workbench, etc). This seems to be a CLIENT_AUTH problem with the latest mySQL version?
index.js
0
I have a Nutanix / Dell 3 node environment, I have managed to change the host Ip addresses to a new subnet and I have also change the CVM ip addresses, but I am having problems finding a way to either change the Cluster IP address from the CLI or break the cluster and rebuild with new IP and name.   Can anyone help?  I am not that conversant with Linux so a simple explanation if possible to get this done.

Many thanks

E.
0
Has been almost a year that I switch to Auth0 in order to manage my customer's access to the dashboard of my application. Nowadays I need to implement access for a RESTFULL API.

If I follow the instructions in order to secure the NodeJS app using JWT it works like a charm. The issue is that I am not properly sure on the implementation for the end user in order to get the token needed for access this API.

I thought of creating the tokens on the dashboard or just use a server side implementation for the login/authentication. I did the last using the access to my own database before and worker amazingly. My issue is that I am not completely sure on how to do it for the end user using Auth0.

Would be great if you can guide me in order to implement the login/authentication side of the API using auth0 and nodejs.
0
I am trying to subtract time now() with data from mysql.
Over here, M_Start = "08:15:00"
Example Current = "22:02:39"
My intention is to get total seconds of the different.
While using moment function : error message : "ReferenceError: moment is not defined (line 22, col 9)"

var ST_Target;
var Shift_Target;

var M_Start = flow.get('Morning_start');
var M_Stop =flow.get('Morning_end');
var M_sec = flow.get('Morning_sec');

var M_cycle = flow.get("Cycle_Time");

var dt = new Date();
var hour = dt.getHours();
hour = ("0" + hour).slice(-2);

var minute = dt.getMinutes();
minute=("0" +minute).slice(-2);

var sec = dt.getSeconds();
sec=("0" + sec).slice(-2);

var current = hour+":" +minute+":"+sec;

var d = moment.duration(current.diff(M_Start[0]));

Open in new window

0
Hi, Experts,

I am building a node JS web app that will call REST API from one login user info.

https://developers.onelogin.com/quickstart/authentication#web-app

spefically from

https://github.com/onelogin/onelogin-oidc-node/tree/master/1.%20Auth%20Flow

the goal is to attain this

https://developers.onelogin.com/openid-connect/api/user-info

but when you use the example curl request you get this:

[code]curl -XGET "https://openid-connect.onelogin.com/oidc/me" \
> -H "Authorization: Bearer 0e4e2d02323de1e71dda7843d968f20425965488d407fbc952927389b63517ac5663"
{"error":"invalid_token","error_description":"invalid token provided"}[/code]

and

[code]curl -XGET "https://domain.onelogin.com/oidc/me" \
> -H "Authorization: Bearer 0e4e2d02323de1e71dda7843d968f20425965488d407fbc952927389b63517ac5663"
{"error":"invalid_token","error_description":"invalid token provided"}[/code]

the flow is API call goes to one login and one login passes access key so you can get user info. when you try to call user info you get an error.

any help would be greatly appreciated.

thank you
0
How to remove mandatory filed check in node js (loopback framework).

I commented below lines from html
<span class="errorForm" ng-show="(profileForm.uOccupation.$dirty || submitted) && (profileForm.uOccupation.$error.required)">
                                                <span class="errorForm" ng-show="profileForm.uOccupation.$error.required">Required</span>
                                            </span>

so now alert is not coming on UI but now page is not submitting.
0
I'm not sure how to get the data from the database into my view. The documentation is pretty sparse on this topic and I'm not really sure how to do it. I suppose that I need to load a `List` in my views/index.js?

views/index.js:
(The Highlight cannot show if the today's date is outside the range of begindate to enddate and the only place that Highlights are shown is on the index page)
    var keystone = require('keystone');
    
    exports = module.exports = function (req, res) {
    
    	var view = new keystone.View(req, res);
    	var locals = res.locals;
    
    	// locals.section is used to set the currently selected
    	// item in the header navigation.
    	locals.section = 'home';
    
        locals.data = {
        	highlights: [],
        };
        
        // Load all highlights
        view.on('init', function (next) {
        
        	var q = keystone.list('Highlight').model.find()
                     .where('begindate').gte(Date.now)
                     .where('enddate').lte(Date.now)
                     .populate('title image content');
        
        	q.exec(function (err, results) {
        		locals.data.highlights = results;
        		next(err);
        	});
        
        });
    
    	// Render the view
    	view.render('index');
    };

Open in new window

Highlights.js - Highlights model:
    var keystone = require('keystone');
    var Types = keystone.Field.Types;
    
    /**
     * Highlight Model
     * ==========
     */
    
    var Highlight = new keystone.List('Highlight', {
    	map: { name: 'title' },
    	autokey: { path: 'slug', from: 'title', unique: true },
    });
    
    Highlight.add({
    	title: { type: String, required: true },
    	image: { type: String },
    	content: { type: Types.Html, wysiwyg: true },
    	begindate: { type: Date, default: Date.now, required: true },
    	enddate: { type: Date, default: Date.now, required: true }
    });
    
    Highlight.schema.virtual('content.full').get(function () {
    	return this.content.extended || this.content.brief;
    });
    
    Highlight.defaultColumns = 'title, image|20%';
    Highlight.register();

Open in new window

Index view,  - highlights block:
    {% block highlights %}
	<!--highlights-starts-->
	<div class="why">
		<div class="container">
			<div class="why-bottom">
				<div class="col-md-12 why-left">				
	{% if data.highlights.results.length %}
		{% for highlight in data.highlights.results %}
					<div class="why-1">
						<img src="{{ image }}" alt="" width="50px"/>
						<div class="why-text">
							<h4>{{ title }}</h4>
							<p>    
							{{ content }}
							</p>
						</div>
					</div>                        
		{% endfor %}
	{% endif %}
					<div class="clearfix"> </div>                    
				</div>	
			</div>
		</div>
	</div>            
	<!--highlights-end-->
    {% endblock %}

Open in new window

When I do it like above, I get this:
    Error compiling twig template C:\wamp\www\hccmks\templates\views\index.twig:
    TwigException: Unable to parse 'data.highlights.results.length'

Open in new window

More help was given on my reddit post but it wasn't resolved...
0
I'm trying to install PhoneGap CLI. When I run this
npm install -g phonegap@latest

Open in new window


I get this
phonegap CLI install error
I have reinstalled Node.js
The versions I have are
Node 10.11.0
npm 5.4.2 (installed when installing Node, I believe)

Can anybody help please?
0
2016 clustered environment . Nodes A crashed after a Ms path so it was rebuilt from an image of node B. I did make sure my ip's are correct.  Now im not able to Ping the private Network. Able to Ping one way only. Can ping from no B to node a. Cannot ping from node a two node be. This is after a crash where I had to rebuild node a from an image of node be. I have reset all settings but this one still has me confused any ideas.
Pings x.x.0.2 on nobe b to node a x.x.0.3 works.
Not working
Ping x.x.0.3  to x.x.0.2
Even isolated ping by typing.
Ping X.x.0.3 -S x.x.0.2
Still not pinging private network (heartbeat)
1
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.

Hi,

In node red, while i insert the - timestamp datatype its work perfectly. while try to select data with the time stamp, its display different time.

Data insert in mariadb ----> 2018-09-19 23:47:26

While select data
if (Device > 0)
    msg.topic ="Select DeviceId, Line, outPIN, count,Time FROM mytab LIMIT 1";

return msg;

Open in new window


While try pull data out of mariadb the data timestamp show --> 2018-09-19 00:20:00
1
Hi I am selecting data from mysql database in node red: -

my database value are as follows:-
dbtime.png
Code in node red as follows: -
 msg.topic ="Select DeviceId, Line, outPIN, count,Time FROM mytab LIMIT 1"

Open in new window


In debug node i do get the time in different format and unable to store in different location of database.

9/17/2018, 4:59:29 PMnode: 4f250b1.97196f4
INSERT INTO mytable1 (DeviceId,Line,outPIN,count,Time) VALUES (?,?,?,?,?) : msg.payload : array[5]
[ 2, 1, "7", 1, "2018-09-16T13:28:24.000Z" ]
9/17/2018, 4:59:29 PMnode: d00874f1.76f388
msg : error
"Error: ER_TRUNCATED_WRONG_VALUE: Incorrect datetime value: '2018-09-16T13:28:24.000Z' for column 'Time' at row 1"

Open in new window



How i can format the time back to normal 'yyyy-mm-dd hh:mm:ss'
0
Hi,

I wanted to develop print solution for my web app : Web app to Desktop print appl using microsoft stack.

when someone press print button on web app, web app may send something like push notification as COMMAND to desktop application (User specific) and upon receipt of command Desktop print app can print the documents. If case of failure Desktop Print Application can send back information to web app about print failure.

To send push notification from web app to Desktop app,
can i use SignalR for sending user specific push notification ?

Please suggest :

1.Am i going in right direction.Whether the industry standards use same process like Google Print or PrintNode.

If not what technology/Process i can use for such application.
Initialy developing for one customer but need for multiple users.

regards,
0
Connection Error: No Mongos proxy available.

Environment: Node.js, MongoDB, Mongoose

Start.js
const mongoose = require('mongoose');


mongoose.connect(process.env.DATABASE,  { useNewUrlParser: true })
mongoose.Promise = global.Promise;
mongoose.connection
  .on('connected', () => {
    console.log(`Mongoose connection open on ${process.env.DATABASE}`);
  })
  .on('error', (err) => {
    console.log(`Connection error: ${err.message}`);
  });

.env file

DATABASE=mongodb://username:DBpassword@player-shard-00-00-1cmur.mongodb.net:27017,player-shard-00-01-1cmur.mongodb.net:27017,player-shard-00-02-1cmur.mongodb.net:27017
0
Error message:  Node 'server' failed to form a cluster. This was because the witness was not accessible. Please ensure that the witness resource is online and available.

The virtual server is up and running and doesn't seem to have any problems but it will not become a part of the cluster.   The server node shows as being down and both the ISCSI connection and Public connections are down
0
Any Zurb Foundation users on here? I am getting the below errors when opening Foundation.

Version info:

Git = v2.13.2

Node = v7.1.0

NPM = v3.10.10

Foundation-CLI = v2.2.5

----------------------------------------------------

1)      I open the console/CMD Prompt
2)      Try to run:
-      foundation –v (to check Foundation CLI version)
-      -or -
-      foundation new (to start a new project)
3)      Get the error


SyntaxError: Unexpected token function

    at Object.exports.runInThisContext(vm.js:78:16)

    at Module._compile (module.js:545:28)

    at Object.Module._extensions..js(module.js:582:10)

    at Module.load (module.js:490:32)

    at tryModuleLoad (module.js:449:12)

    at Function.Module._load(module.js:441:3)

    at Module.require (module.js:500:17)

    at require (internal/module.js:20:19)

    at Object.<anonymous>(C:\Users\*****\AppData\Roaming\npm\node_modules\foundation-cli\node_modules\terminal-kit\lib\termkit.js:53:26)

    at Module._compile (module.js:573:32)

---------------------------------------

In PATH = Git then NPM then Nodejs

‘foundation –v’  -or- ‘foundation new’ resultsin:

C:\Users\*****\AppData\Roaming\npm\node_modules\foundation-cli\node_modules\terminal-kit\lib\detectTerminal.js:179

exports.getParentTerminalInfo = async functiongetParentTerminalInfo( callback ) {

                                                                     ^^^^^^^^
0

Node.js

135

Solutions

265

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
>