Node.js

267

Solutions

367

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 was show how to access the responsXML once for my list.  I am trying figure out how to get to the nodes again.  The last time I did it, it was with Chrome Developer tools in the browser.

I have a function like this:

function myFunction(responseXML) {
		console.log(responseXML);
		var itemList = [];
		console.log(responseXML.getElementsByTagName("entry"));
		for (var i = 0; i < responseXML.getElementsByTagName("entry").length; i++) {
			id = responseXML.getElementsByTagName("entry")[i].childNodes[0].childNodes[0].nodeValue;
			title = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[5].childNodes[0].nodeValue;
			header = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[7].childNodes[0].nodeValue;
			urlDescription = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[8].childNodes[0].childNodes[0].nodeValue;
			url = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[8].childNodes[1].childNodes[0].nodeValue;
			methodType = responseXML.getElementsByTagName("entry")[i].childNodes[20].childNodes[0].childNodes[9].childNodes[0].nodeValue;
			itemList.push(new Item(id, header, title, url, urlDescription, methodType));
		}

Open in new window

0
Success in ‘20 With a Profitable Pricing Strategy
Success in ‘20 With a Profitable Pricing Strategy

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!

Node.js and EJS

I have a html page in node js using ejs template wherein i have main checkbox for Hobbies(x) with id hobby with checkbox check by default once the page loads .and underneath i have 5 options(a,b,c,d,e) . these sub checkbox underneath hobbies are also checked by default.

I am wondering how do i write a java script function inside node.js router so that when box is unchecked no result should get displayed in node.js console and i should be able to send data to mongodb collection.

Please note that i am able to access the checkbox with id req.body.hobbyid when selected and send this data to backend server. However when i unselect the parent checkbox i am getting that value is undefined in node.js console.

Code snippet below

if (req.body.hobby[0]) {
      console.log(a); //here x can be any value
}
if (req.body.hobby[1]) {
      console.log(b); //here y can be any value
}
if (req.body.hobby[2]) {
      console.log(c); //here x can be any value
}
if (req.body.hobby[3]) {
      console.log(d); //here y can be any value
}

// code to connect to mongodb which i am not giving here which works very well when i check the main checkbox for hobby.

I want to achieve a way wherein when main parent checkbox(here which is hobby with id hobbymain is unchecked it should store a value as "False" and set the value as "Not submitted" in db and store in some variable which i can later pick the send to backend server.

Please note that when all checkbox are checked it …
0
Ran the command npm start to boot up my Magic Mirror with the MMM-Facial-Recognition module and I am given this error.  I am not sure how to fix it.The error I am given
0
I am using sequelize in node.js. At the moment I can search multiple tables and produce the the results as data.  I have done so using the following code:

router.get("/alldata", (req, res) => 

Promise.all([chemical_bays.findAll(), electricals.findAll(), fire_services.findAll(), instruments.findAll(), mechanicals.findAll(), microwaves.findAll(), tools.findAll(), water_cays.findAll(), buildings.findAll(), substations.findAll(), fences_gates_cctv.findAll(), steam_plant_other.findAll(), information_technology.findAll(), ])
.then((data) => {  res.render('gigs', {gigs: [...data[0], ...data[1], ...data[2], ...data[3], ...data[4], ...data[5], ...data[6], ...data[7], ...data[8], ...data[9], ...data[10], ...data[11], ...data[12]] }) }).catch(err => console.log(err)));

Open in new window


However, I wish now to count the results and have them displayed, however, if I use the aggregate attribute, "count", I am receiving an error. Here is the code I am trying to use:

router.get("/alldata", (req, res) => Promise.all([chemical_bays.findAll({attributes: ['id', [sequelize.fn('count', sequelize.col('id')), 'count']],
group : ['chemical_bays.id'],
raw: true,
order: sequelize.literal('count DESC')}), electricals.findAll({attributes: ['id', [sequelize.fn('count', sequelize.col('id')), 'count']],
group : ['electricals.id'],
raw: true,
order: sequelize.literal('count DESC')}), fire_services.findAll({attributes: ['id', [sequelize.fn('count', sequelize.col('id')), 'count']],
group : 

Open in new window

0
I'm getting some error like this:

MongoError: E11000 duplicate key error collection: auth.users index: email_1 dup key: { email: "damianjnc114444455@gmail.com" }

Any ideas?

my code

https://github.com/damianjnc/server-authentication/tree/665d5bd2ac7e2b346d2616d5013311a5ff0cc430
0
hi am geting the following error
ERROR in src/app/tasks/tasks-add/tasks-add.component.ts:24:17 - error TS2345: Argument of type '(newTask: Task) => void' is not assignable to param
eter of type '(value: Task[]) => void'.
  Types of parameters 'newTask' and 'value' are incompatible.
    Type 'Task[]' is missing the following properties from type 'Task': id, name, completed, dueDate

24                 (newTask: Task) => {
                   ~~~~~~~~~~~~~~~~~~~~

** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
i 「wdm」: Failed to compile.

my code is
import { Component, OnInit } from '@angular/core';
import { Task } from '../task.model';
import {TaskService} from '../task.service';

@Component({
    selector: 'app-tasks-add',
    templateUrl: './tasks-add.component.html',
    styleUrls: ['./tasks-add.component.css']
})
export class TasksAddComponent implements OnInit {

    addTaskValue: string = null;

    constructor(private taskService: TaskService) { }

    ngOnInit() {

    }

    onTaskAdd(event) {
        let task: Task = new Task(event.target.value,false, this.getTodayAsString());
        this.taskService.addTask(task)
            .subscribe(
                (newTask: Task) => {
                    // clear the input
                    this.addTaskValue = ' ';
                    this.taskService.onTaskAdded.emit(newTask);
                }
            )
    }

    getTodayAsString() {

Open in new window

0
I am using the handlebars template in node.js. Currently, the thumbnail images from the database are displaying at a width and height of 70 which is specified in the code. See below. How can I allow the user to click on the image in handlebars and see a larger rendition of the photo?
The current images are too small to see but I would only like for them to be increased upon clicking them.

<img id="img" src="/uploads/{{photo_image}}" width="70" height="70">
0
Hello, I am trying to automate something at work. I cannot use the actual code because the company is picky about privacy. The example I show would be similar and easy for me to use it the same way. I have begun understanding something about using Socket.io. The information I read showed how to connect to a web socket and emit data to connected web sockets. I now realize what web sockets can do. I am aware of how to set up a server and create an index.js file that sets up a connection. My question is how via a command line (Windows 10) could I make a webpage run JavaScript. In the code I show for the index.html page how could it run the sayHello function from a command-line command sent to the page? Thanks

<!doctype html>
<html>
	<head>
		<meta charset="utf-8">
			<title>Untitled Document</title>
			<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.dev.js"></script>	
			<script type="text/javascript">
			
				var h = 'Hello';
				
				var socket = io.connect('http://localhost:4561');
				
				function sayHello() {
					alert(h);
				}
						
			</script>
	</head>

	<body>
	</body>
</html>

Open in new window

0
Can you help with this error.

ran the command npm install --global.

I see the below error

npm ERR! code ENOENT
npm ERR! syscall rename
npm ERR! path /Users/sdatla/build_tools/node-v8.15.1-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-v8.15.1-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-v8.15.1-darwin-x64-npm-5.6.0/lib/node_modules/.staging/Newton-7c7da797/node_modules/@babel/code-frame' -> '/Users/sdatla/build_tools/node-v8.15.1-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-20T18_47_33_888Z-debug.log
0
I need to have this converted to JavaScript or TypeScript whichever is easier.

public static SqlDataReader ExecuteReader(string cmd, SqlConnection sqlConnection, SqlParameter[] parameters = null)
        {

            SqlCommand command = null;

            try
            {
                SqlDataReader result;
                command = new SqlCommand(cmd, sqlConnection);
                command.Connection.ConnectionString = DB_Connection;
                command.CommandType = CommandType.StoredProcedure;
                command.CommandTimeout = 0;
                AssignParameters(command, parameters);
                sqlConnection.Open();
                result = command.ExecuteReader();
                return result;

            }
            catch (Exception ex)
            {
//Error trap system
            }

        }

Open in new window

0
Python 3 Fundamentals
LVL 19
Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

I have added a command in scripts section of package.json to update one of the one of the dependencies.

When i run npm install, is there a way to tell the npm install to pick up specific package.json file?

Not sure how to get the npm install to use the package.json located in a local directory.

If i do a yarn install, i see it uses the package.json that was in the local directory.

If i use npm install -g command, the install does not use package.json from the local directory.
0
Hi. I need to write a javascript parser. My goal is to fetch the object definition given an oid.

This is the file :
http://www.net-snmp.org/docs/mibs/SNMPv2-MIB.txt

Info
https://docstore.mik.ua/orelly/networking_2ndEd/snmp/ch02_05.htm

Thank you.
0
So, I have deployed what I have done on my project so far to Heroku only to discover that that any images you upload to their server are deleted periodically! Not super helpful.

https://help.heroku.com/K1PPS2WM/why-are-my-file-uploads-missing-deleted

So, that means I have to either store the images in the database which I don't want to do, or upload to a cloud server. Before setting this up, I was using sharp to resize and compress the uploaded image. So, I uploaded the file into memory, resized/compressed it and then wrote it to a new file. I am uploading to google cloud storage.

I have the upload to the cloud working but it is uploading the original image, not the resized one. I think that it is because the cloud upload isn't uploading the one from memory but rather the original uploaded file.

This is the route:

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

Open in new window


Controllers

// save image to memory instead of to disk
const multerStorage = multer.memoryStorage();

const upload = multer({
  storage: multerStorage,
  fileFilter: multerFilter
});

// upload the image
exports.uploadUserPhoto = upload.single("bgImg");

//resize and compress image
exports.resizeUserPhoto = (req, res, next) => {
  if (!req.file) return next();

  req.file.filename = `hero-${Date.now()}.jpeg`;

  // get the image from memory
  sharp(req.file.buffer)
    .resize(1800, 948, {
      fit: sharp.fit.outside
    })
    .toFormat("jpeg")
    .jpeg({ quality: 80 })
    .toFile(`public/img/${req.file.filename}`);

  next();
};

Open in new window



Open in new window

0
Needs some advice regarding REACT with an Express front end for API database requests.  I have added the proxy entry the package.json file.  However, the api requests are still be served by the REACT app.  I need some advice on what I am doing wrong.

Here is my package.json file:
{
"name": "ubwo",
"version": "0.1.0",
"private": true,
"proxy":"localhost:5000/",
"dependencies": {
"react": "16.8.6",
"react-dom": "16.8.6",
"react-redux": "7.1.0",
"react-router": "5.0.1",
"react-router-dom": "5.0.1",
"react-scripts": "3.0.1",
"redux": "4.0.1",
"redux-thunk": "2.3.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"resolutions": {
"browserslist": "4.6.2",
"caniuse-lite": "1.0.30000974"
}
}

Open in new window

0
Hi,

I am trying to establish communication between HMI and PLC by using the Raspberry Pi. The existing setup between HMI directs to PLC via serial communication and protocol on Modbus RTU.

I am trying to put Raspberry Pi between HMI and PLC. Raspberry pi will be master serial to pull data from PLC via Serial Modbus RTU and be slave serial for HMI. HMI will be master to pull data from raspberry pi.

How I can achieve this? I am trying this to get some extra data from plc for monitoring purpose and didn't disturb the existing system.
0
I am attempting to write code in node.js to edit a record which has a file location for the image's url in the database.  I was able to edit all the other field columns pretty well. However, it appears that for security reasons, editing a image is not easily allowable....but there must be a workaround this in order to edit a record with an image file's url to upload another image. I keep getting this message:

Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

Here is my code for the form file upload:
<label for="file">Profile Photo:</label>
        <input type="file" name="image" id="image" onChange={this.uploadFile}>
        <br><br>

Open in new window



Here is the frontend code for editing all records which I added the image value to:

$(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);
      $("#image", "#modalStationForm").val(value.Image);
  

Open in new window

0
I have a file  from CA (certificate authority) .crt file with multiple BEGIN CERTIFICATE and END CERTIFICATE snippets inside.  I have a node js program to make my site https.
This program takes sslKey": "private-key.pem", sslCertificate": "lws-cert.pem". Now i assume i have the .crt file which can be renamed as lws-cert.pem and used in the program and what about private key ?
Am i missing something ? Is my aproach correct ?
0
I need to performance tune front end application running in node js ,d3 js , html , javascript , css with express server and  with back end in war file  done in sbt deployed on tomcat using spark scala mongdb hive kafka mysql hadoop. Let me know the best tools to monitor and performance tune the app for speed , good response etc., Thank you in advance.
0
So I have an update form and I want to prepopulate it. I also want to execute the update method as well. I am having some issues on how I can approach that problem. Below I have a screen shot,back end and also front end code

Update and prepopulating form using react
second.post('/student_info',(req,res)=>{
  const student_id = req.body._id;
  db.collection('students').find({"_id" : ObjectID(student_id)}).toArray((err,result) => {
    if(!err) {
       res.send(result);
    } else {
        console.log(err);
    }

  });

Open in new window



second.post('/students/updateStudent', (req, res) => {
   try {
    db.collection('students').updateMany( {"_id" : ObjectID(req.body._id)},
      { $set: { role_num:req.body.role_num, first_name: req.body.first_name, last_name: req.body.last_name, marks: req.body.marks}});
 } catch (e) {
  console.log(e);
 }
    res.send('student updated');
 });

Open in new window

import React, {Component} from 'react';
import './App.css';
import axios from 'axios';
export default class EditStudent extends Component {
constructor(props) {
  super(props)
  this.ChangeID = this.ChangeID.bind(this);
  this.ChangeRoleNumber = this.ChangeRoleNumber.bind(this);
  this.ChangeFirstName= this.ChangeFirstName.bind(this);
  this.ChangeLastName = this.ChangeLastName.bind(this);
  this.ChangeMarks = this.ChangeMarks.bind(this);
  this.Enter =  this.Enter.bind(this);

  this.state = {
     _id: '',
     role_num: '',
     first_name: '',
     last_name: '',
     marks: ''

  }
}

Open in new window

0
11/26 Forrester Webinar: Savings for Enterprise
11/26 Forrester Webinar: Savings for Enterprise

How can your organization benefit from savings just by replacing your legacy backup solutions with Acronis' #CyberProtection? Join Forrester's Joe Branca and Ryan Davis from Acronis live as they explain how you can too.

When trying to run gulp, I get the error: ReferenceError: primordials is not defined

??
1
I'am new to TestCafe and website testing. I startetd my first test with TestCafe and it works well. Now I want to add some functions and own steps to it but  have problems to understand the usability a little bit.

I want to find a element o the site. Only if this element do not exists I want to start some actions. If the element exists I want to jump. I think the best way is to make a function inside the script, but I have no idea how. Anyone can help me how to find an element with TestCafe, as sample a label "testvalue" and only do some actions if not found?
0
I want to prepopualate my forms

Snapshot_19-05-08_10-59-40.png
Snapshot_19-05-08_11-00-41.png
Above I have two screen shots The first screen shot is a prepopulated form and the second screen shot shows the
rest of the movies listed from 7-20 by id number. I wanted to know how I can prepopulate the rest of the fields because when I click on
the field that starts with 7 or 20 for example the same information shows up for the movie name that begins with 5

<html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
    <link href="mystyle.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
      <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
    <script src="mycrud.js"></script>
    </head>
    <body>
    <title>My Movies</title>
    <header>
        <h1>Movies</h1>
    </header>
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel"
         aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div 

Open in new window

0
So unfortunetly my data is not updating even though I get a status request of 200 ok below are my front end and back end code
and below I have a screen shot and my front end and back end code I do not know why it is not updating in the front end when I do it on postman it does update and the querry works

data-not-updating.png
app.put('/movielist/updateMovie/:id',(req,res) =>{
  let update = req.body;
  mysqlConnection.query("UPDATE movielist SET name = '', thumnail_path = ?, description = ?, year_released = ?, language_released = ? WHERE idmovielist = ?",
 [update.name,update.thumnail_path,update.description,update.year_released,update.language_released,req.params.id],function (err, results) {
    if (!err) {
      res.send("Movie list is updated");
    } else {
      console.log(err);
    }
  });
});

$(function() {
  //Fill the list when the page loaded
  renderMovieList('movies');

  $("#movieAdded").click(function(a) {
    a.preventDefault();

    let mydata = {
      idmovielist: $($("#newForm")[0].intNum).val(),
      name: $($("#newForm")[0].name).val(),
      thumnail_path: $($("#newForm")[0].thumnail_path).val(),
      description: $($("#newForm")[0].description).val(),
      year_released: $($("#newForm")[0].year_released).val(),
      language_released: $($("#newForm")[0].language_released).val(),
    }

    displayMovie(mydata);

    $("#newForm").trigger("reset");
    $("#newForm").toggle();
  });

  $("#updateMovie").on("click", function(a) {
    

Open in new window

0
Snapshot_19-05-01_18-37-48.png

So I have an sql errror when whenever I update my data

const express = require('express');
const app = express();
const mysql = require('mysql');
const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
const mysqlConnection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'Adil@123',
  database: 'movies'

});
mysqlConnection.connect(err=>{
  if (err) {
    console.log('It was not successful \n Error:' + JSON.stringify(err,undefined,2));
  } else {
    console.log('Its a success');
  }
  });
 //  Collecting all the movies from the movielist
  app.get('/movielist',(req,res)=> {
    mysqlConnection.query("SELECT * FROM movielist", (err, rows,fields)=> {
      if (!err) {
        res.send(rows);
      } else {
        console.log(err);
      }
    });
  });
 // Finding a movie based on the `idmovielist` number
   app.get('/movielist',(req,res) => {
    mysqlConnection.query("SELECT * FROM movielist WHERE idmovielist = ?",[req.params.id],(err, rows,fields) =>{
    if (!err) {
      res.send(rows);
    } else {
    console.log(err);
    }
    });
  });

  // Delting a movie
   app.delete('/movielist/:id',(req,res) => {
    mysqlConnection.query("DELETE FROM movielist WHERE idmovielist = ?",[req.params.id],(err,rows,fields) =>{
      if (!err) {
        res.send("Movie is deleted");
      } else {
      console.log(err);
    }
    });
  });
  // Inserting

Open in new window

0
Put-ui-front-end.png

Above I have a screen shot of my PUT method and when ever I execute it I get no response from the network tab and I have a additional modal that pops up behind when ever I click update. Below I will show you my front end and also back end in node js.

<html>
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width">
    <link href="mystyle.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
      <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
    <script src="mycrud.js"></script>
    <script>
    $.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>" +
            

Open in new window

0

Node.js

267

Solutions

367

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
>