Node.js

246

Solutions

361

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

What is it about Node that makes it difficult if not impossible to host on a shared server?

I'm assuming it's because you have to be able to log directly into the server using SSH, but why? What is it about Node that requires that kind of approach?
1
Introduction to Web Design
LVL 13
Introduction to Web Design

Develop a strong foundation and understanding of web design by learning HTML, CSS, and additional tools to help you develop your own website.

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
I am looking to build an alternative to Zapier "zap" using a digital ocean droplet. Can anybody recommend a technology? The first thing that comes to mind is Node.js or PHP. Zapier is great, and we love it, however we are now being asked to processes files with up to 10,000 lines per file per month. This brings our zapier bill from @20 per month to $300. I would like to have a webHook online with custom URL. (myDomain.com/myWebHook)

our zap is very simple:
* push FirstName, LastName, Email to a webook
* add the user to a mail chimp list
* add the user to a wordPress memberPress subscription
* send the user a custom welcome email from an office 365 account

There are a few reasons it might make sense to build our own integration tool:
1 ) if we are going to get 10,000 items to process every month or so, it it much nicer to just budget $50 per month for an AWS or Digital Ocean VM
2 ) During the memberpress user create, then add to the correct subscription, the smallest time pause that Zapier allows is 1 minute. When we are processing 10K of new users, this can extend out for quite some time. It might be easier to have the ability to control down to a 15 second wait time.
3 ) I am not sure how zapier runs each zap, but during the memberPress adds it might be nice to know they are all running in serial. I often wonder if zapier runs them in parallel. We frequently get DB timeout errors when the zaps are running.

What I am looking for is advice on the following:
1
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
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
Ensure you’re charging the right price for your IT
Ensure you’re charging the right price for your IT

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!

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
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
JavaScript Best Practices
LVL 13
JavaScript Best Practices

Save hours in development time and avoid common mistakes by learning the best practices to use for JavaScript.

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

Node.js

246

Solutions

361

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
>