Node.js

179

Solutions

312

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 the code that it's in the tutorial that I'm going through:

Controller:

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

exports.getProducts = (req, res, next) => {
  Product.fetchAll(products => {
    res.render("shop/product-list", {
      prods: products,
      pageTitle: "All Products",
      path: "/products"
    });
  });
};['/code]

That's referencing the "fetchAll" method in the "product.js" file in the "models" directory which looks like this:

[code]static fetchAll(cb) {
    getProductsFromFile(cb);
  }

Open in new window


...and that's referencing the "getProductsFromFile" method in the same class...

const getProductsFromFile = cb => {
  fs.readFile(p, (err, fileContent) => {
    if (err) {
      return cb([]);
    }
    cb(JSON.parse(fileContent));
  });
};

Open in new window


I understand the flow, but I was curious as to why the "fetchAll" method was necessary.

Could you not just do this:

static getProductsFromFile(cb);

Open in new window


It seems like there's an unnecessary layer of code there.

I haven't even tried it, but I wanted to ask why you need "fetchAll" if the sole purpose of that function seems to be just triggering another function.

Am I missing something and, if so, what?
0
Active Protection takes the fight to cryptojacking
LVL 2
Active Protection takes the fight to cryptojacking

While there were several headline-grabbing ransomware attacks during in 2017, another big threat started appearing at the same time that didn’t get the same coverage – illicit cryptomining.

what are some of the things, that are important in web development.

things like -
- choosing a particular platform / technologies or language  like Node js , which is very popular in modern day, for rapid development
- what  security vulnerabilities, that absolutely needs to be addressed. what are some techniques  to address those.
-  what other techniques should one keep in mind - caching techniques, load balancing etc.
0
Capture35.PNG
I have an issue with my put request it says status 404 not found
$(function(){
$("#showMovies").click(function() {
  $.ajax({
    method:"GET",
    url: "http://localhost:3000/movielist",
    dataType: "json",
    success: function (response) {
      $.each(response, function(i, movie) {
	    const rowText = "<tr>" +
          "<td>" + movie.idmovielist + "</td>" +
          "<td>" + movie.name + "</td>" +
          "<td>" + movie.thumbnail_path + "</td>" +
          "<td>" + movie.description + "</td>" +
          "<td>" + movie.year_released + "</td>" +
          "<td>" + movie.language_released + "</td>" +
          "<td>" + "<button button id = \"deleteMovie\" type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal\">Delete</button>" + "</td>" +
          "<td>" + "<button button id = \"editMovie\" type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal\">Edit</button>" + "</td>";
        $("#movies").append(rowText);
      });
    }
  });
});

$("#movieAdded").click(function() {
  $.ajax({
    method:"POST",
    url: "http://localhost:3000/movielist/addMovie",
    dataType: "json",
    data: {
       idmovielist: 10,
       name: 'Bubble Gum',
       thumnail_path: 'yourieiri.jpg',
       description: 'Disturbing',
       year_released: '2007',
       language_released: 'french'
    },
    success: function (data) {
      $.each(data, function(i, movie) {
	    const 

Open in new window

0
UImyexecute.zip

Above I have two files and the first one is a picture of my UI the problem is all the infromation in my ui is displaying in only one column of my table not in seperate columns. What can I
do to fix this
0
Hi Experts,
I have created map with googles map react with markers and infow window, I am working on dragging the marker into a new location, I can drag the marker but I dont know how to save its new location in the state, so when I refresh the map, the marker will stay at the new locatoin.
any help will be appreciated .
here import React, { Component } from 'react';
import axios from 'axios';
import {Map, InfoWindow, Marker, GoogleApiWrapper} from 'google-maps-react';


const style = {
  width: '100%',
  height: '100%'
}

class MapContainer extends Component {

 
   constructor (props){
     super(props);
     this.state = {
     position:  {lat: 51.56613,
     lng: -3.76831},
     showingInfowWindow: false,
     activeMarker: {}, /**shows the active marker upon click */
     selectedPlace:{}, /** shows the infowindow to the selected places upon a marker */
     sensors: [] ,
     markers: []
    };
  }
 


   onMarkerDragStart = (event) => {
    const {latitude, longitude} = event;
  }

  onMarkerDragEnd = (event) => {
    const {latitude, longitude} = event;
    this.setState({latitude, longitude})
  }

  onMarkerDrag =(event) => {
    const {latitude, longitude} = event;
  }

  /**we need to add event handler when the map and the marker are clicked */
  componentDidMount() {
     axios.get('http://localhost:5000/aqm/data/display')
      .then(response => {
         this.setState({sensors:response.data})
          console.log(response.data);
        
    });  
  

Open in new window

0
We have  a pair of servers running Windows 2008 (no R2) Enterprise Server using the Cluster. The cluster is running fine for several years.


Today I login to the server using domain account that is in the local Administrators group., I tried to "Validate a Configuration: but it gave me error:
"Failed to validate node 'sp01.nt.local'. An error occurred while determining if you have administrator privileges on 'sp01.nt.local'. Attempted to perform an unauthorized operation. BTW the cluster still running fine.

What  did go wrong?


Thank you,

Iwan
0
Hello
I am trying to authenticate my API calls using JWT with nodejs and javascript using qeuelize and mysql . I was able to get the token and send it in the headers using postman, but if i want to send it from the html form once the user sign in and then the token will be send or go through to authenticate the user. how will I store the token so the user can send it with the middle ware to be reauthorized to access the index page.
signin function:

exports.signIn = (req, res) => {
	console.log("Sign-In");
	console.log(req.body.username);

	User.findOne({

		where: {
            username: req.body.username,
		}
	}).then(user => {
	    console.log(user.password);
		if (!user) {
			return res.status(404).send('User Not Found.');
		}
        let passwordIsValid = bcrypt.compareSync(req.body.password, user.password);
        if (!passwordIsValid) {
			return res.status(401).send({ auth: false, accessToken: null, reason: "Invalid Password!" });
		}

        const token = jwt.sign({id: user.id}, config.secret, {
            expiresIn: 86400 // expires in 24 hours
        });


       // res.status(200).send({ auth: true, accessToken: token });
       res.sendFile(path.resolve(__dirname,'../public/index.html'));


    }).catch(err => {
		res.status(500).send('Error -> ' + err);
	});
};
/************************************** verifyToken function****************/
verifyToken = (req, res,next) => {
  const token = req.headers ['x-access-token'] || 

Open in new window

0
Hi
I am running Node.js app to check for connectivity and reboot if the timer reaches 0, and I am logging the status on a log file but when I run this code as a snap on ubuntu core, I can not find where the log files are in snap.
here is my code:
#!/usr/bin/env node
const moment = require('moment');
const shutdown = require('electron-shutdown-command');
const electron = require('electron');

const fs = require('fs');

let counter = 0;

function checkInternet(cb) {
    setInterval(function(){
    require('dns').lookup('google.com',function(err) {
        if (err && err.code ===  "ENOTFOUND") {
            cb(false);
        } else {
            cb(true);
        }
    }); }, 30000);
}

function rebootEdgeBox(){
    shutdown.reboot();
    console.log('Shutting down now');
   
}


checkInternet(function (isConnected) {
        if (isConnected) {
            console.log('alive');
             counter =0;
        } else {

            const timeStamp = moment().format('YYYY-MM-DD, HH:mm:ss');
            const status = 'Disconnected at ' + timeStamp;
            console.log(status);
            counter += 1;
            vortexLog(status);
            if (counter === 10){
                counter = 0;
                console.log('ji');
               rebootEdgeBox();


            }
        }

    });

function vortexLog(string) {
    fs.appendFile('./Logs/connectionLog', string + "\r\n", function (err) {
        if (err) throw …
0
Upgrade from VCSA 6.5 U1 to VCSA 6.7U1  done in HA mode but with warning
VCHA Upgrade is done but some details required to automatically create clones for Passive and Witness nodes could not be fetched. Delete the source Passive and Witness VMs and make two new clones of the upgraded Active node that will serve as new Passive and Witness VMs. VCHA Cluster should be set to Enabled after Passive and Witness join the cluster. Check documentation for configuring VCHA cluster manually.
Does anyone have additional information about this?
Thank you
0
Hi
I am new to javascript and I am writing a program with nodejs and javascript to get the ip address and hostname of my computer and log them to mysql table, I need to insert a new row each time the ipp address changes with the time stamp. the problem that how to insert the new row at the end of the table if the ip address changes..
can anyone help me please as I was trying for few days. i have used the for loop to loop through each row and insert at after the last row, but when the insert statement executes it inserts many rows at the same time with the loop.

#!/usr/bin/env node
const publicIP = require('public-ip');
const pool = require('./database/config');
const moment = require('moment');
const os = require ('os');
const ip = require("ip");
var async = require('async');

setInterval(function () {

    (async () => {
        try {
            const IPv4 = await publicIP.v4();
            const hostname = os.hostname();
            const timestamp = moment().format('YYYYY:MM:DD, HH:mm:ss');

            //const sql = "SELECT id, ip_add, host_name,active FROM ipaddresses WHERE host_name = host_name" ;
            //const sql = "SELECT id, ip_add, hostname,timestamp FROM ipaddress" ;
            const sql = "SELECT  * FROM ipaddress order by id desc limit 1";    
           //async.forEachOf(rows, function(value, key, callback){
               var result =[];
                pool.query(sql,IPv4,(error, rows, fields) => {
                         …
0
Ensure Business Longevity with As-A-Service
Ensure Business Longevity with As-A-Service

Using the as-a-service approach for your business model allows you to grow your revenue stream with new practice areas, without forcing you to part ways with existing clients just because they don’t fit the mold of your new service offerings.

I have the following:
//index.js
router.get('/', catchErrors(deviceController.findRoute));

//deviceController.js
exports.findRoute = async (req, res) => {
  if (req.user) {
    const devices = await Device.find({ owner: req.user._id });
    if (!devices.length) {
        res.redirect('/store');
    } else {
       res.redirect('/devices');
    }
  } else {
    res.redirect('/store');
  }
}

//authController.js
exports.login = passport.authenticate('local', {
  failureRedirect: '/login',
  failureFlash: 'Failed Login',
  successRedirect: '/',
  successFlash: 'You are now logged in'
});

Open in new window


My issue is flash messages get lost on redirects to "/". How do I pass the flash messages to findRoute?
0
I am looking for a simple (complete) example for a client-side (Javascript or html form)  and server-side NODE.JS data exchange or query.
0
say for example, I want to read a text file or do some processing on a input file by running a javascript code on node js.

is there a good package in node/npm to perform read/write operations to a file.

I am new to node js and server side javascript programming.
0
Somebody has a good example autocomplete search nodejs, express, mongodb
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 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_modules?

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 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
Acronis Global Cyber Summit 2019 in Miami
 Acronis Global Cyber Summit 2019 in Miami

The Acronis Global Cyber Summit 2019 will be held at the Fontainebleau Miami Beach Resort on October 13–16, 2019, and it promises to be the must-attend event for IT infrastructure managers, CIOs, service providers, value-added resellers, ISVs, and developers.

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
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
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
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
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

Node.js

179

Solutions

312

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.