Node.js

232

Solutions

351

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

I am getting an error when I run my node app using sequelize - 'Unknown column \'general_comments\' in \'field list\''. However, as seen below, I have a model with the column....general_comments.  Please see the error log below and the model code for compressor

Server started on port 5000
Executing (default): SELECT 1+1 AS result
Connection has been established successfully.
http://localhost:5000/api/alldatac:2019-09-19T05:03:25-04:00
Executing (default): SELECT `compressor_house_id`, `equipment_area`, `equipment_type`, `photo_image`, `manufacturer`, `model_number`, `serial_number`, `service`, `capacity`, `severity`, `general_comments`, `createdAt`, `updatedAt` FROM `compressor_houses` AS `compressor_house`;
{ SequelizeDatabaseError: Unknown column 'general_comments' in 'field list'
    at Query.formatError (C:\Users\Chrystelle\Omar Martin\Dropbox\web design\hurricane_dorian\node_modules\sequelize\lib\dialects\mysql\query.js:244:16)
    at Query.handler [as onResult] (C:\Users\Chrystelle\Omar Martin\Dropbox\web design\hurricane_dorian\node_modules\sequelize\lib\dialects\mysql\query.js:51:23)
    at Query.execute (C:\Users\Chrystelle\Omar Martin\Dropbox\web design\hurricane_dorian\node_modules\mysql2\lib\commands\command.js:30:14)
    at Connection.handlePacket (C:\Users\Chrystelle\Omar Martin\Dropbox\web design\hurricane_dorian\node_modules\mysql2\lib\connection.js:408:32)
    at PacketParser.Connection.packetParser.p [as onPacket] (C:\Users\Chrystelle\Omar 

Open in new window

0
Should you be charging more for IT Services?
Should you be charging more for IT Services?

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

Record
I am using the "each statement" with the handlebars template engine in node.js.  Unfortunately, each record is being tabbed to the right of the previous one, as the attach image shows. I would like each record to line up evenly.
Please see the code:

Here is the file:gigs.handlebars

{{#each gigs}}
<section id="gigs" class="container">
<!--<h1>All Gigs</h1>-->
<h1>{{equipment_area}}</h1>
<div class="gig">
      <h3>{{title}}</h3>
      <!--<p>{{manufacturer}}</p>-->
      <ul>
        <!--<li>Budget: {{budget}}</li>-->
        <!--<li><a href="mailto:{{contact_email}}" class="btn btn-reverse">Apply Now</a></li>-->
        <li>Equipment Type: {{equipment_type}}</li>
        <li>Manufacturer: {{manufacturer}}</li>
        <li>Model Number: {{model_number}}</li>
        <li>Serial Number: {{serial_number}}</li>
        <li>Condition: {{severity}}</li>
        <li>Comments: {{general_comments}}</li>
                
      </ul>
      <!--
      <div class="tech">
        <small>Technologies Needed: <span>{{technologies}}</span></small>
      </div>
      -->
    </div>
    {{else}}
     <p>No gigs available</p>
    {{/each}}
</section>

Open in new window


Please also see the css file:
@import url('https://fonts.googleapis.com/css?family=Lato');

:root {
  --primary-color: #568c9b;
  --primary-hover-color: #64a5b7;
  --bg-color: #333;
  --box-shadow: 3px 4px 12px rgba(0, 0, 0, 0.7);
}

* {
  box-sizing: border-box;
}

body {
  font-family: 'Lato',

Open in new window

0
I have an xml declared as:
declare @xmlIndata xml = '<root>
  <FromDate>2018-04</FromDate>
  <ToDate>2019-08</ToDate>
  <Period />
  <Units>
    <Unit>
      <Name>1</Name>
    </Unit>
  </Units>
  <Variables>
    <Variable>
      <Name>N05C</Name>
    </Variable>
    <Variable>
      <Name>N06A</Name>
    </Variable>
    <Variable>
      <Name>PeopleCount</Name>
    </Variable>
  </Variables>
  <Filters />
</root>'

Open in new window


I want to extract the subtree starting at the node <Variables>.  So some xml manipulation to extract the subtree and set it to @variables. Like:

declare @variables xml
set @variables = somehow select the subtree 'Variables' from xmlIndata;

Then @variables should be:
 ' <Variables>
    <Variable>
      <Name>N05C</Name>
    </Variable>
    <Variable>
      <Name>N06A</Name>
    </Variable>
    <Variable>
      <Name>PeopleCount</Name>
    </Variable>
  </Variables>'

Open in new window

seems pretty basic to be able to extract part of an xml but i cant find out how to do it.
0
This works:

const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
const mongoose = require("mongoose");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const csrf = require("csurf");

const MONGODB_URI =
  "mongodb+srv://username:password@brucegust-wxyz.mongodb.net/applied";

app.get("/api", (req, res) => {
  //console.log("hello");
  res.json({
    message: "Welcome to the API"
  });
});

app.post("/api/posts", verifyToken, (req, res) => {
  jwt.verify(req.token, "secretkey", (err, authData) => {
    if (err) {
      res.sendStatus(403);
    } else {
      res.json({
        message: "Post created",
        authData
      });
    }
  });
});

app.post("/api/login", (req, res) => {
  //Mock User
  const user = {
    id: 1,
    username: "brad",
    email: "email@domain.com"
  };

  jwt.sign({ user: user }, "secretkey", { expiresIn: "30s" }, (err, token) => {
    res.json({
      token: token
    });
    console.log("yes");
  });
});

// format of Token
// Authorization: Bearer <access_token>

//verify Token

function verifyToken(req, res, next) {
  //get auth header value
  const bearerHeader = req.headers["authorization"];
  // check if bearer is undefined
  if (typeof bearerHeader !== "undefined") {
    // split at the space
    const bearer = bearerHeader.split(" ");
    //get token from array
    const bearerToken = bearer[1];
    console.log(bearerToken);
    

Open in new window

0
HI this is a continuation of thread from before
old thread

the conditions for this project has changed a little rendering the script that Michelangelo had provided no longer useful for my cause although it worked for the previous purpose

heres what changed:
the files in questions are XML format (but are not named .xml they are .901 files)
i need to remove a whole node from the *.xml files ,  including the tag

i.e.
 <errsql yadadayda > 
random sql error the statement has terminated
</errsql>

this whole line need to be removed form the file

here is a snippet of the xml file:

<chgsql ts="07:01:58.971" op="O" jb="ADD" tb="CLL_TAB" sc="BATCH"> <fld fd="F1000" af="PAL"/>
<fld fd="F1148" af="43000135163"/>
<idx fd="F1577" af="5167599565"/>
<idx fd="F1578" af="LINK"/>
<fld fd="F1001" af="1"/>
<fld fd="F902" af="00003814"/>
</chgsql>
<errsql ts="07:01:58.986" op="O" lv="50" ob="">
<sql>INSERT INTO CLL_TAB [F1000,F1148,F1577,F1578,F1001,F902] VALUES [:F1000,:F1148,:F1577,:F1578,:F1001,:F902] </sql>
<prm>PAL,43000135163,5167599565,LINK,1,00003814,</prm>
</errsql>
<chgsql ts="07:01:58.986" op="O" jb="ADD" tb="CLL_TAB" sc="BATCH">
<fld fd="F1000" af="PAL"/>
<fld fd="F1148" af="43000135164"/>
<idx fd="F1577" af="5166282554"/>
<idx fd="F1578" af="LINK"/>
<fld fd="F1001" af="1"/>
<fld fd="F902" af="00003814"/>
</chgsql>
0
I have been working towards creating a multiplayer three.js fps game and am planning to only do client-side prediction in the browser. On the other hand, I am using Node.js Express.js and Socket.io for the authoritative server-side implementation of the multiplayer game and would like to check collision server-side.

Using three.js or external libraries, what are the possible options to create a headless version of the game state like the babylon.js-nullengine and calculate raycasting collision on the server-side?

Similarly, how do three.js multiplayer io-based games keep track of game states server-side and do bullet and movement collision?
1
I have created a node.js API and use React to get data from the API and display it on the frontend. I however need to start doing some simple SEO work like titles and meta descriptions etc. but not sure how to do this.

I installed React Helmet and in Google console if I look at the elements I can see the title and description there but I don't think that is enough to show up for search engines?

          <Helmet>
            <title>My page title</title>
            <meta name="description" content="Helmet application" />
          </Helmet>

Open in new window

0
structure
I am attempting to render a view through the template engine "handlebars" for node.js with the express framework. Please see attached my file structure.  After running the route below, I keep receiving the following error: [Error: Failed to lookup view "layout" in views directory "C:\Users\frontstart\Dropbox\Web Design\nodetest\views"]. Can someone please help me locate my error.


router.get("/alldata", (req, res) =>
  Store.findAll()
    .then(stores => {
        path is //views/gigs.handlebars
        res.render('gigs', {
              stores
        });
       })
    .catch(err => console.log(err)));

module.exports = router;

Here is the backend app.js

const fs = require("fs");
const express = require("express");
const expressSession = require("express-session");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const path = require("path");
const expressLayouts = require("express-ejs-layouts");
const mysql = require("mysql");
const mysql2 = require("mysql2");
const multer = require("multer");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");
const Joi = require("@hapi/joi");
const connectFlash = require("connect-flash");
const morgan = require("morgan");
const passport = require("passport");
const passportLocal = require("passport-local");
const Sequelize = require("sequelize");
const db = require("./middleware/db.js");
const 

Open in new window

0
I am using  Joi (Happy) module in node.js to validate entries into a form to a mysql database.  However, the validation does not work. I am receiving a "TypeError: Cannot read property 'path' of undefined" every time I leave the file field empty.  Nothing occurs when I leave any other field empty.  In other words, the validation simply does not work and no field message is being sent to the user based on the entry criteria. Please see the backend and the frontend code using sequelize. Without validation, the form works fine.

FRONTEND CODE WITH FORM:

<!DOCTYPE html>
<html lang="en">
<head>
  <!--JQuery UI: default css (smoothness)(always first)-->
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css"> 


  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>

  <!--JQuery (always first)-->
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>

<!--JQuery UI core (always first)-->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<!--JQuery UI(after JQuery UI core) - Controls Dialog Modal -->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 

</head>
<body>
  <!---(8)-->
  <h3>Inserting Data into the database</h3>
  <h3>Data List</h3>
  <div id="storesF">
  <div 

Open in new window

0
Installed node version: v10.16.2
               npm version: 6.10.3

When i run the command 'npm install -g'

Got the below error.

npm ERR! code ENOENT
npm ERR! syscall rename
npm ERR! path /Users/sdatla/build_tools/node-v10.16.2-darwin-x64-npm-5.6.0/lib/node_modules/.staging/Newton-7c7da797/node_modules/@babel/code-frame
npm ERR! dest /Users/sdatla/build_tools/node-v10.16.2-darwin-x64-npm-5.6.0/lib/node_modules/.staging/@babel/code-frame-bbf22dc8
npm ERR! errno -2
npm ERR! enoent ENOENT: no such file or directory, rename '/Users/sdatla/build_tools/node-v10.16.2-darwin-x64-npm-5.6.0/lib/node_modules/.staging/Newton-7c7da797/node_modules/@babel/code-frame' -> '/Users/sdatla/build_tools/node-v10.16.2-darwin-x64-npm-5.6.0/lib/node_modules/.staging/@babel/code-frame-bbf22dc8'
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/sdatla/.npm/_logs/2019-08-19T14_43_17_871Z-debug.log

Please help
0
HTML5 and CSS3 Fundamentals
LVL 13
HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

I have manually updated package.json file on my local directory.

I did npm install globally using the below command.

npm install npm@latest -g

It created a package.json file from the install. Is there a way to point package.json from my local directory?
0
I was in a meeting today with my co-workers where our boss announced that we're going to start building out a project in Node.

I've been going through a Node Tutorial and I've made a point of taking thorough notes, but there were some terms being thrown around in the meeting and I have them below. I'm taking a crack at defining them, but I wanted some other eyes on this so I can both sound intelligent and begin working in a way that's sound.

First, what is an ETL? I was looking at this article, but I've not run into this before. Here's the link: https://blog.panoply.io/6-top-level-etl-tools-for-node.js-and-2-paid-etls

Throughout the meeting, the phrase "spec it out" was used. I'm assuming that refers to documenting what it is that needs to be done after having analyzed the job, correct?

Data Point - another term that was being thrown around. After looking it up, it looks as though a data point is a piece of information. A last name could be a data point, correct?

Swagger - the project I'm working is grabbing info from Mac's Healthkit and making it available in our company's application. An API is going to be part of the process, obviously, and I get the impression that Swagger is a part of the process. How? (https://blog.cloudboost.io/adding-swagger-to-existing-node-js-project-92a6624b855b)

Stoplight - seems like this is similar to Swagger. What is it and what is its function?

FHIR - I'm reading through this article: …
0
I would like to select a record from a mysql database by "id" using sequelize.  I currently can do it with a mysql query and it works but I am receiving a null result when attempting to do it in sequelize.  Here is the query in my mysql which works and the query in sequelize which does not work. What am I doing wrong with the syntax in the sequelize version?




``````````````````````````````````````````````````````````````````````````````
        (1)

        router.get("/station/number/:id", (req, res) => {
      db.query(
            "SELECT * FROM stores WHERE id = ?",
            [req.params.id],
            (err, rows, fields) => {
                  if (!err) res.send(rows);
                  else console.log(err);
            }
      );
});


       (2)
 
      router.get("/station/number/:id", (req, res) =>

      Store.findOne ({
      where: {id:'?'}})
      .then(data=>{
     res.send({stores:data})
      })
     .catch(err => console.log(err)));
0
I am new to sequelize and I created a middleware called "db.js" with a connection to a mysql table called "users". Everytime, I attempt to run the app.js, I am getting this error: "TypeError: app.use() requires a middleware function".

However, I have a middleware function. See the code below: Am I missing something? I have the module.exports object at the end.

Should I have initialize sequelize?

Here is the db.js file:
const Sequelize = require("sequelize");
const mysql = require("mysql");
const mysql2 = require("mysql2");

const db = {}
const sequelize = new Sequelize("smalldata", "root", "xxxx", {
    host: "localhost",
    dialect: "mysql",
    operatorsAliases: false,

    pool: {
        max: 5,
        min: 0,
        acquire: 30000,
        idle: 90000
    }
})

sequelize
    .authenticate()
    .then(() => {
        console.log('Connection has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

db.sequelize = sequelize
db.Sequelize = Sequelize

module.exports = db;

Open in new window


Here is the app.js file:


const sequelize = require("sequelize");
const db = require("./middleware/db");
const express = require("express");

//Initialize Middleware
app.use(cors());
app.use(expressLayouts);
app.use(logger);
app.use(db);

Open in new window



Here is the users.js file for the mysql table:

const Sequelize = require("sequelize");
const db = require("./db");

const User = db.sequelize.define(
    'users',
    {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },

        first_name: {
            type: Sequelize.STRING
        },

        last_name: {
            type: Sequelize.STRING
        },

        email: {
            type: Sequelize.STRING
        },

        password: {
            type: Sequelize.STRING
        }
    },

    {
        timestamps: true
    },
)

// Note: using `force: true` will drop the table if it already exists
User.sync({ force: true }).then(() => {
    // Now the `users` table in the database corresponds to the model 
    definition
    return User.create({
        first_name: 'John',
        last_name: 'Hancock',
        email:'johnhancock@gmail.com',
        password:'johnny'
    });
});

module.exports = User

Open in new window

0
I have a profile photo which the user can update. What SHOULD happen is that when they upload a new photo, the database is updated and the old photo is deleted. However, what is happening is that the database is updated correctly, but the newly uploaded image is deleted meaning there is no image at all now. I also tried deleting the file synchronously using fs.unlinkSync but had the same result.

const multerStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "public/img");
  },
  filename: (req, file, cb) => {
    const ext = file.mimetype.split("/")[1];
    cb(null, `hero-${Date.now()}.${ext}`);
  }
});

// test if uploaded file is an image
const multerFilter = (req, file, cb) => {
  if (file.mimetype.startsWith("image")) {
    cb(null, true);
  } else {
    // throw error here
    cb(console.log("not an image"), false);
  }
};

const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter
});
exports.uploadUserPhoto = upload.single("bgImg");

Open in new window



exports.updateHeroImg = async (req, res) => {
  const updateId = "5d13b3c6dd57c43828ed5a7a";
  if (req.file) bgImgNew = req.file.filename;
  //find current image name in database
  const hero = await Hero.findById(updateId);
  if (!hero) return;

  // helper function to delete files
  fileHelper.deleteFile("public/img/" + hero.bgImg);

  // set new db record image name
  hero.bgImg = bgImgNew;

  // update database
  const result = await hero.save();
  res.status(200).send("image uploaded");
};

Open in new window

Helper delete function

const fs = require("fs");

const deleteFile = filepath => {
  fs.unlink(filepath, err => {
    if (err) {
      throw err;
    }
  });
};

exports.deleteFile = deleteFile;

Open in new window


My route:

router.post("/", heroController.uploadUserPhoto, heroController.updateHeroImg);

Open in new window

0
Hi,

I would like to use nodejs for enabling an ad user to upload a local file to a server. It should be uploaden in a folder with the ad users name.
Have no experience with nodejs.
Please advise howto.

Note: have working code in powershell, now need a web interface for it.

J
0
Hi guys,
I am trying to check login in a external website and I am using node.js.
the site I am trying to check the login contain form that submit username and password:
Here is the dom of this website:
<form action="/PSAWeb/login" id="LoginForm" method="post" novalidate="novalidate">        <div class="sixteen columns">
            
            <div id="FakeSummary" class="validation-summary-errors">
                <ul id="validation-ul"></ul>
            </div>
        </div>
        <fieldset class="five columns">
            <legend>Log In</legend>
            <ol>
                <li>
                    <label for="Username">Username</label>
                    <input data-val="true" data-val-required="The Username field is required." id="Username" name="Username" type="text" value="">
                </li>
                <li>
                    <label for="Password">Password</label>
                    <input id="Password" name="Password" required="Required" type="password" class="form-control" autocomplete="off" aria-required="true">
                    <span toggle="#Password" style="float:right; margin-right:5px; margin-top:-30px; position:relative; z-index:2; display:none;" class="togglePassword"><i class="icon-eye-open icon"></i></span>
                </li>
                    <li>
                        <label for="Schema">Database</label>
                        <div id="SchemaChosen">
                            <span 

Open in new window

0
I am trying to display unique records grouped by the particular slug passed in.

My output in postman looks like this though:

	"subcats": [
	  {
		"_id": {
		  "subcategory": {
			"_id": "5d2b42c47b454712f4db7c37",
			"name": "shirts"
		  }
		}
	  }
	]

Open in new window


My desired output would be more like:

"subcats": [
  {
        "_id": "5d2b42c47b454712f4db7c37",
        "name": "shirts"
  }
]

Open in new window

An example of a product in the database:

 
       "_id": "5d39eff7a48e6e30ace831dc",
        "name": "A colourful shirt",
        "description": "A nice colourful t-shirt",
        "category": {
            "_id": "5d35faa67b19e32ab3dc91ec",
            "name": "clothing",
            "catSlug": "clothing"
        },
        "subcategory": {
            "_id": "5d2b42c47b454712f4db7c37",
            "name": "shirts",
            "catSlug": "shirts"
        },
        "price": 19
    }

Open in new window


I don't want that top level `_id` there with everything nested inside of it.

I tried using `$project` but then I just end up with an empty array.

      const products = await Product.find({ "category.catSlug": catslug }).select({
        name: 1,
        description: 1,
        price: 1,
        category: 1
      });

    const subcats = await Product.aggregate([
      { $match: { "category.catSlug": catslug } },
      { $group: { _id: { subcategory: "$subcategory" } } }
      { $project: { _id: 0, name: 1 } }
    ]);

    Promise.all([products, subcats]);
      res.status(200).json({
        products,
        subcats
      });

Open in new window

0
I am trying to understand node/javascript async / promise features.  While doing this I ran across an example that confuses me.  Here is the example, and the questions are below:
From https://codeburst.io/javascript-promises-explained-with-simple-real-life-analogies-dd6908092138

const loadImage = url => {
  return new Promise(function(resolve, reject) {

    //Open a new XHR
    var request = new XMLHttpRequest();
    request.open('GET', url);

    // When the request loads, check whether it was successful
    request.onload = function() {
      if (request.status === 200) {
        // If successful, resolve the promise
        resolve(request.response);
      } else {
        // Otherwise, reject the promise
        reject(Error('An error occurred while loading image. error code:' + request.statusText));
      }
    };

    request.send();
  });

};

Open in new window


1. Why create a promise for this?  Isn't XMLHttpRequest already async?  It makes a request, and then you feed onload a function to call when it is done.
2. onload documentation says, "to be executed when the request completes successfully".  So in the example above onload is used for a resolve or a reject.  If onload only fires on success how would the failure portion of the IF (line 13) every be reached?
0
Announcing the Winners!
LVL 13
Announcing the Winners!

The results are in for the 15th Annual Expert Awards! Congratulations to the winners, and thank you to everyone who participated in the nominations. We are so grateful for the valuable contributions experts make on a daily basis. Click to read more about this year’s recipients!

I have the following code to insert, edit and delete records from a database using node.js.  I would like to have alert messages informing the user of the successful transaction for each from the frontend if successful.  I am not certain regarding the syntax for this.

Here is the code to insert into the database:
$(document).ready(() => {
    $(document).on('click', '.insert', function (e) {
     // $('#insertD').click(() => {
      e.preventDefault();
      $("#insertE").remove();
      $("#insertD").show();
      $("#stationForm")[0].reset();
      $("#stationForm").attr({
        action: $(e.target).attr("href"),
        //action: "/station", // PATH TO POST NEW STATION DATA ?
        method: "POST"
      });
   
      $("#modalStationForm")
        .dialog("option", "title", "Inserting New Station")
        .dialog("open");
      });
[/code}


Here is the code edit code:
[code]
$(document).ready(() => {
    $(document).on('click', '.edit', function (e) {
      e.preventDefault();
      $("#insertD").hide();
      $("#insertE").show();
      $("#stationForm")[0].reset();
      $("#stationForm").attr({
        action: $(e.target).attr("href"),
        //action: "/station", // PATH TO POST NEW STATION DATA ?
        method: "PUT"
      });
      var value = $(event.target).closest("div").find("input:hidden").val();
      value = JSON.parse(value);

      $("#store", "#modalStationForm").val(value.Station);
      $("#location", 

Open in new window

0
After attempting to edit a mysql record in node.js, I am receiving null results when I review the mysql query report and the affected rows are returning zero.  There is no change to the record. However, the backend says that the results are not null, the sql query is not null and that the req.body for all the values are not null.

Here is the mysql general query log:

190717 16:42:40	    3 Query	SELECT * FROM stores
		    3 Query	SELECT * FROM stores
		    3 Query	SELECT * FROM stores
190717 16:42:42	    3 Query	SELECT * FROM stores
190717 16:43:13	    3 Query	UPDATE stores SET `station` = NULL, `address` = NULL, `monthly c-store sales` = NULL,`operator` = NULL, `top sku` = NULL WHERE `id` = NULL

Open in new window


These are the results returned on the frontend:

affectedRows: 0
changedRows: 0
fieldCount: 0
insertId: 0
message: ""
protocol41: true
serverStatus: 2
warningCount: 0

Open in new window


However, the backend says that the values are not null after putting in the following code:

if (results !== null) {
        console.log('results is not null');
        }else{
        console.log('results is null');
        };


      if (sql !== null) {
      console.log('sql is not null');
      }else{
      console.log('sql is null');
      };

      if (req.body.Station !== null) {
        console.log('req.body is not null');
        }else{
        console.log('req.body is null');
        };

Open in new window


Here are the results.....
{ station: 'Hopefully',
  address: 'this',
  monthlycstoresales: '200',
  operator: 'will',
  topsku: 'work',
  id: '7' }

results is not null

sql is not null

req.body is not null

Open in new window



Here is the backend code:

Open in new window

0
I'm supporting a spark scala application with node js front end with d3 js etc.,. The spark uses spark job server for taking in api requests in the form of curl json inputs and return back json outputs. I'm getting a too many open files issues.

09:27:23.649 [task-result-getter-1] WARN  o.a.spark.scheduler.TaskSetManager - Lost task 0.0 in stage 151.1 (TID 10373, localhost, executor driver): java.io.FileNotFoundException: /data/iot/installs/data/spark_work/blockmgr-952fad2f-2721-41da-a513-aebc7fc83c1a/35/shuffle_65_0_0.index.ffe8ecd3-64ab-445f-8fa7-8ba9aefcdeff (Too many open files)
      at java.io.FileOutputStream.open0(Native Method)
      at java.io.FileOutputStream.open(FileOutputStream.java:270)
      at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
      at java.io.FileOutputStream.<init>(FileOutputStream.java:162)
      at org.apache.spark.shuffle.IndexShuffleBlockResolver.writeIndexFileAndCommit(IndexShuffleBlockResolver.scala:144)
      at org.apache.spark.shuffle.sort.BypassMergeSortShuffleWriter.write(BypassMergeSortShuffleWriter.java:127)
      at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:96)
      at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:53)
      at org.apache.spark.scheduler.Task.run(Task.scala:109)
      at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:345)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
      at …
0
Data Tables are not being displayed with data from the database.  I am receiving the following error:

jquery.dataTables.min.js:40 Uncaught TypeError: Cannot read property 'length' of undefined

Here is the code:

<!--Data Tables:css-->
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
<!--Data Tables-->
    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>

$(document).ready(function () {
$('#datatable').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "http://localhost:5000/alldata",
"type": "GET"
},
"columns": [
{ "data": "ID" },
{ "data": "Station" },
{ "data": "Address" },
{ "data": "C-Store Sales" },
{ "data": "Operator" },
{ "data": "Top SKU" }
]
});
});

Open in new window


<!---(2b)-->
    <h3>Data Table</h3>
    <form id="form1">
      <table class="table table-bordered table-striped" id="datatable">
        <thead>
          <tr>
            <th>ID</th>
            <th>Station</th>
            <th>Address</th>
            <th>C-Store Sales</th>
            <th>Operator</th>
            <th>Top SKU</th>
          </tr>
        </thead>
      </table>
    </form>

    <hr>

    <br />

Open in new window

0
I'm going through a Node tutorial and I'm at the point where I'm working with "express-validator."

According to the docs, "express-validator" is "...a set of express.js middlewares that wraps validator.js validator and sanitizer functions."

Easy enough, but I want to better understand that definition and it's bugging me that I've never installed the "validator.js" library.

Here's what I understand:

Middleware acts as a bridge between two applications. In the context of Node, Express is middleware specifically in the way it intercepts and interacts with the request and the response objects that are coming from the DOM (feel free to stop me at any time if I'm not accurate).

A "wrapper," according to https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_wrap_element, is something that's going to "wrap" around a div...

So, going back to the original definition, it looks as though Express-Validator is wrapping around the "validator.js" library and making it more intuitive to use.

But where does "validator.js" come from? I've never installed it, so how did that become use-able?

And then when I look at the example of the Jquery "wrap" method (https://www.w3schools.com/jquery/html_wrap.asp)...

How does express-validator "wrap" around validator.js?
0
Hello expert,

Have an Excel spreadsheet on complex project called 'SFTP'.
Excel spreadsheet has a ton of detail on project
but there is so much info that it is hard to see where one
customer is in the SFTP set up process.

So created a Visio that details the process and then
inserted the customers showing where the
customers were in the process, attached.

It would be great if clicking on the Visio customer
node would take the user to the line in Excel
for that customer.

Have tried a couple of online tutorials about how to
link Visio to Excel.
https://classroom.synonym.com/visio-objects-excel-13927.html

But this and others like it explain how to link a Visio
shape to Excel data. All that is required for this project
is to link a Visio shape or text to a row or cell in Excel.

Is this possible?

A link has been created in the past using JavaScript
to create a hot spot on a GIF in an HTML file
that links to another HTML file.

But I was hoping that Microsoft had integrated
there apps enough to go between Visio and Excel

Thanks.

Allen
Payer_TPA_SFTP_process_190701.gif
0

Node.js

232

Solutions

351

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
>