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:


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"

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

[code]static fetchAll(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([]);

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?
Active Protection takes the fight to cryptojacking
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.
I have an issue with my put request it says status 404 not found
$("#showMovies").click(function() {
    url: "http://localhost:3000/movielist",
    dataType: "json",
    success: function (response) {
      $.each(response, function(i, movie) {
	    const rowText = "<tr>" +
          "<td>" + movie.idmovielist + "</td>" +
          "<td>" + + "</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>";

$("#movieAdded").click(function() {
    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) {

Open in new window


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
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){
     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() {
      .then(response => {

Open in new window

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,

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) => {


		where: {
            username: req.body.username,
	}).then(user => {
		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:}, config.secret, {
            expiresIn: 86400 // expires in 24 hours

       // res.status(200).send({ auth: true, accessToken: token });

    }).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

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) {
    require('dns').lookup('',function(err) {
        if (err && err.code ===  "ENOTFOUND") {
        } else {
    }); }, 30000);

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

checkInternet(function (isConnected) {
        if (isConnected) {
             counter =0;
        } else {

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



function vortexLog(string) {
    fs.appendFile('./Logs/connectionLog', string + "\r\n", function (err) {
        if (err) throw …
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
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) => {
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:
router.get('/', catchErrors(deviceController.findRoute));

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

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?
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.
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.
Somebody has a good example autocomplete search nodejs, express, mongodb
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;

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

Open in new window

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

--node_modules folder

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?
I am just getting started with Angular (

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?

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

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?
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='';
		//For each loop passing results variable through the Object.Keys method. 
		var row= results[key];

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

Open in new window

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.


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;

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


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 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 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) - API URL2 (auth guards - OPENID) - Current state you land at …
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.
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?
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.
Hi, Experts,

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

spefically from

the goal is to attain this

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

[code]curl -XGET "" \
> -H "Authorization: Bearer 0e4e2d02323de1e71dda7843d968f20425965488d407fbc952927389b63517ac5663"
{"error":"invalid_token","error_description":"invalid token provided"}[/code]


[code]curl -XGET "" \
> -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






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.