Node.js

243

Solutions

360

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 trying to control a bit of AV equipment using the TCP control API. Here is a screenshot of the command I am trying to build.
Screenshot-2019-05-04-at-21.49.58.png
This is currently my code:
con = 3017; //0xC9 0x0B
cpu = 1012; //0xF4 0x03
cmd = Buffer.from([
     0x1B,
     0x5B,
     0x49,
     0x09,
     0x00,
     parseInt(con || 0, 10),
     parseInt(cpu || 0, 10)
]);

Open in new window


My output is:
1B 5B 49 09 00 C9 F4

But I want to get this:
1B 5B 49 09 00 C9 0B F4 03

I think it's because the CON & CPU are 2 bytes, but I don't know how to fix it.

Please can someone help
0
I have some data in a text file which looks like this?

id=1, some text here, status=waiting
id=2, some other text here, status=waiting
I am reading the code with this:

Open in new window


fs.readFileSync('mytextfile.txt', 'utf-8').split(/\r?\n/).forEach(function(line) {

  if (line.includes('status=waiting')) {

    var nameArr =  line.split(',');
    var arrayLength = nameArr.length;
    for (var i = 0; i < arrayLength; i++) {

        console.log(nameArr[i]);
        //NEEDED: Finally change status=waiting to status=completed and save it // This is what I need
    }

  }

});

Open in new window

After I read it I need to change the status part of it and save it.

How do I do the part marked: NEEDED ?
0
The following code works:

exports.postCart = (req, res, next) => {
  const prodId = req.body.productId;
  let fetchedCart;
  let newQuantity = 1;
  req.user
    .getCart()
    .then(cart => {
      fetchedCart = cart;
      return cart.getProducts({ where: { id: prodId } });
    })
    .then(stuff => {
      let product;
      if (stuff.length > 0) {
        product = stuff[0];
      }
      if (product) {
        const oldQuantity = product.cartItem.quantity;
        newQuantity = oldQuantity + 1;
        return product;
      }
      return Product.findByPk(prodId);
    })
    .then(product => {
      return fetchedCart.addProduct(product, {
        through: { quantity: newQuantity }
      });
    })
    .then(() => {
      res.redirect("/cart");
    });
};

Open in new window


This is Sequelize and I believe I'm about to be completely impressed because of what is apparently in place with "fetchedCart.addProduct."

It would seem that Sequelize knows by virtue of the "Magic Methods" anomaly that it knows whether or not to add a new row or simply update an existing one.

Is that true? And if so, where is there some documentation that elaborates on that?

Thanks!
0
If I need to run an unknown number of functions in a specific order what is the best way to do this using Async await?

For example...if I have:

function func1() { //does something }
function anotherfunc() { //does something }
function func3() { //does something }

Open in new window


The number of functions above could be 3 or 10.

Then using async away, I need to call them in order:

So I have another function called process:

function process() {
  func3(); 
 func1();
 anotherfunc() ;
}

Open in new window


function process needs to run the functions in the order that they are placed and each has to finish before the other one starts.

How can I do this?
0
I have some code that uses async / await and promises.

The example code uses setTimeouts for demo purposes.

Basically it demonstrates how to control the order of when function results are shown.

Here is the sample code:

async function job1(){
    const p = await new Promise(resolve => setTimeout(resolve, 10000)).then(()=>'Job1');
    console.log('Completed job1');
    return p;
}

async function job2(){
    const p = await new Promise(resolve => setTimeout(resolve, 2000)).then(()=>'job2');
    console.log('Completed job2');
    return p;
}

  async function processJobs() {

    const p1 = job1();
    const p2 = job2();
     
    let m1 = await p1
    let m2 = await p2 
    
    console.log(`"${m1}" and "${m2}" are complete.`);
    return (`"${m1}" and "${m2}" are complete.`);

 }

Open in new window


What I need is a demonstration on how to uses this code about without timers and still have the result in the order I want it.

For example I'll add 2 functions below to be replaced:

function job1() {
  const fs = require('fs');
  fs.writeFile("source/test.txt", "Hey there!", function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 
}

Open in new window


and the second:

function job2() {
 fs.createReadStream('source/test.txt').pipe(fs.createWriteStream('target/test.txt'));
}

Open in new window


As you can see job1() needs to be completed before job2() can start.

How can I adapt these 2 functions to the sample code above?
0
I have a txt file which contains some data that I need to read and finally modify after reading it.

The file data looks like this:

id=1; myfunction1 params; myfunction2 params; status=waiting;
id=2; myfunction1 params; myfunction2 params; status=waiting;
id=3; myfunction1 params; myfunction2 params; status=waiting;

Open in new window

The function I was thinking would be something like:

function readAndModify(filename) {

    // Read first line if status is waiting:
    if (line.includes('status=waiting')) {
        // do something with the read content
        // change status=waiting to status=complete and save changes
    }   
}


readAndModify('mytextfile.txt');

Open in new window

My question is...

How can I do this part change
status=waiting to status=complete 

Open in new window

and save changes ?
0
Hello,

There are 2 existing files i am working on. One is :

Test.js
Test.js.map

So if i need to update Test.js how to do it (As everything is referenced from a source map file).
So browser picks up source map file as the primary source. (Test.js.map)

How to update the source map file or is there any other option if i can detach this file permanently and so that code can be referenced just from Test.js file.

Never used .map file before.

Thanks.
0
I've text file like below and i'd like to read them by row number and assign their values automatically to Windos Form textbox control.

How is it possible to read specific rows (in my file desired values' row index is 2,5,8,11...) and assign their value to my application's textbox.

######## Log File for RBE2 elements (Be careful to have write permission to folder, file names are not important)
C:\Users\USER1\Desktop\Sample_BIF\condensRun_13042019\test4.log

######## Log File copy for RBE2 elements(Be careful to have write permission to folder, file names are not important)
C:\Users\USER1\Desktop\Sample_BIF\condensRun_13042019\test4_copy.log

######## Excel file to get set id to delete
C:\Users\USER1\Desktop\Sample_BIF\condensRun_13042019\input_condensationPrep.xlsx

######## Excel file sheet number
1

######## Column for Delete?
3

######## Column for Set ID
4

######## First Row of SetIDs (Source)
2

######## Last row of SetIDs (Source)
12

######## Sleep Time
10000

######## Column for Leaf Spring Property ID
6

######## Column for Reference Nodes
7

######## Column for Interface Nodes
8

######## BUSHING STARTS - Changed node number start. This number will be the start point while renumbering
12001

######## Bush properties K1
150000

######## Bush properties K2
200000

######## Bush properties K3
300000

######## Bush properties K4
400000

######## Bush properties K5
500000

######## Bush properties K6
600000

######## Bush property ID
120

######## Bush 

Open in new window

0
Here's the code:

module.exports = class Cart {
  static addProduct(id) {
    //fetch the previous cart
    fs.readFile(p, (err, fileContent) => {
      let cart = {products: [], totalPrice: 0}
      if(!err) {
        cart = JSON.parse(fileContent);
      }
    });
    //analyze the cart => find existing product
    [b]const existingProduct = cart.products.find(prod=>prod.id===id);[/b]
    //add new product / increase quantity
  }
};

Open in new window


I'm using this as my academic starting point in order to understand why this works: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

...tell me if I'm explaining this correctly.

existingProduct is a variable that's either going to return the matching product id or "undefined" based on whether or not the "id" that's being evaluated matches anything in the already existing products array which is a property belonging to the "cart" object.

This:

cart.products.find(prod=>prod.id===id);

Open in new window


...is akin to this:

for(products as prod) {
   if(prod.id=id)
    {
       //we've got a match
    }
    else
    {
          //undefined...
    }
}

Is that right? And if not, what am I missing?
0
Here's my code:

let cart = {products: [], totalPrice: 0}

Open in new window


If I were explaining this to someone, I would say that "cart" is an object with two properties: an empty array called "products" and a "totalPrice" property with a value of 0.

Is that correct?
0
Here's the code that it's in the tutorial that I'm going through:

Controller:

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

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

Open in new window


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

static fetchAll(cb) {
    getProductsFromFile(cb);
  }

Open in new window


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

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

Open in new window


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

Could you not just do this:

static getProductsFromFile(cb);

Open in new window


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

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

Am I missing something and, if so, what?
0
Here's my function:

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

Open in new window


fetchAll looks like this:

static fetchAll(cb) {
    getProductsFromFile(cb);
}

Open in new window


...and getProductsFromFile looks like this:

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

Open in new window


Tell me, please, if I'm explaining this correctly. I'm attempting to understand this stuff to the degree when I can explain it to others and I'm having a hard time.

What I've been taught / told is that I'm looking at an expression that's being passed as an argument to another function. That's the quintessential advantage / utility of a callback.

So, this:

products => {
res.render("shop/product-list", {
prods: products,
pageTitle: "All Products",
path: "/products"
}

Open in new window


...is being passed as an argument to:

static fetchAll(cb) {
    getProductsFromFile(cb);
}

Open in new window


BTW: An expression represents the "guts" of a function, correct?

Thing is, if I try to envision that based on face value, I see something like this:

static fetchAll(products => {
res.render("shop/product-list", {
prods: products,
pageTitle: "All Products",
path: "/products"
}) {
    getProductsFromFile(products => {
    res.render("shop/product-list", {
    prods: products,
    pageTitle: "All Products",
     path: "/products"
     });
}

Open in new window


That seems both convoluted and bogus.

I'm thinking that for all intents and purposes, the "getProductsFromFile" method would be written like this:

getProductsFromFile(products)

Open in new window


Instead of:

products => {
    res.render("shop/product-list", {
    prods: products,
    pageTitle: "All Products",
     path: "/products"
     });
}

Open in new window



All the examples I've seen have very basic functions being used to illustrate what a callback is. This is far more complex and, as a result, seems a little more complicated.

What I'm "smelling" is that when you pass this:

products => {
res.render("shop/product-list", {
prods: products,
pageTitle: "All Products",
path: "/products"
}

Open in new window


...as an argument into:

static fetchAll(cb) {
    getProductsFromFile(cb);
}

Open in new window

0
Is there a way to store vue compontents into a database?

I want to create the ability for users to create a email templates. Each template would be different and require two parts

1) the template its self populated with content ( Hi {{name}} )
2) the data to replace the placeholder content( {{name}} )

i dont see much issues with storing the templates and accessing the data

1) Get data (template and replacement data)

im not sure how i could
2) load the template into vue dynamically
3) parse the template and update the placeholder with actual data

in php, i would just use str_replace which i guess i could do with replace() but that is just working with strings. Im curious if there is a vue way to accomplish this
0
I'm working through a tutorial on Node and we recently invoked a callback and I'm wanting to pop the hood on all this just so I've got a firm grasp of the subject matter.

This code is part of the lesson and it works:

exports.getProducts = (req, res, next) => {
  Product.fetchAll(products => {
    res.render("shop", {
      prods: products,
      pageTitle: "Shop",
      path: "/",
      hasProducts: products.length > 0,
      activeShop: true,
      productCSS: true
    });
  });
};

Open in new window


I want to break it down and be able to write something much simpler that illustrates what's happening and how it works.

First of all, arrow functions...

This:

function lidiexy(products) {
	console.log(products);
}
	
lidiexy(4);

Open in new window


...can be written like this:

const bill=lidiexy(products) => {
      console.log(products);
}

bill(4);

Open in new window


The above code is using the ES6 version of code. I'm using an arrow function and "const bill..." is now an anonymous function because it doesn't have a name.

BTW: I'm stating things as, what I believe to be accurate explanations. Let me know if I'm correct.

This:

lidiexy (products) => {
     console.log(products);
}

Open in new window


...is tecnically referred to as the "body" of the function. I would have to attach this to a "const" or a "let" to fire it correct?

The reason I'm asking this is because, in the tutorial I'm going through, we're doing something like this:

function david(cb) {
	cb("george")
}

david(products=> {
	console.log(products);
});

Open in new window


This works and I understand the callback (cb) dynamic. But what puzzles me is why it works. If "products" in the context of  "david(products) is a parameter, then how does the code know to treat that as a function?

This:

products => {
    console.log("hello");
}

...doesn't work by itself. I can't call that as "products();"

And yet, I can pass it in as is and it fires correctly.

Why?

Is that just the way an anonymous function is processed when it's being asserted as an argument?

Thanks!
0
I'm working through a Node.js tutorial and, while my code works, I want to understand why it works.

First of all, here's the relevant code:

products.js (controller)

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

exports.getAddProduct = (req, res, next) => {
  res.render("add-product", {
    pageTitle: "Add Product",
    path: "/admin/add-product",
    formsCSS: true,
    productCSS: true,
    activeAddProduct: true
  });
};

exports.postAddProduct = (req, res, next) => {
  console.log(req.body.title);
  const product = new Product(req.body.title);
  product.save();
  res.redirect("/");
};

exports.getProducts = (req, res, next) => {
[b]  Product.fetchAll(products => {
    res.render("shop", {
      prods: products,
      pageTitle: "Shop",
      path: "/",
      hasProducts: products.length > 0,
      activeShop: true,
      productCSS: true
    });[/b]
  });
};

Open in new window


shop.ejs

<%- include('includes/head.ejs') %>
    <link rel="stylesheet" href="/css/product.css" />
  </head>

  <body>
    <%- include('includes/navigation.ejs') %>

    <main>
      <h1>My Products</h1>
      <p>List of all the products...</p>
      [b]<% if(prods.length>0) { %>[/b]
      <div class="grid">
        <% for (let product of prods) { %>
        <article class="card product-item">
          <header class="card__header">
            <h1 class="product__title"><%= product.title %></h1>
          </header>
          <div class="card__image">
            <img
              src="https://cdn.pixabay.com/photo/2016/03/31/20/51/book-1296045_960_720.png"
              alt="A Book"
            />
          </div>
          <div class="card__content">
            <h2 class="product__price">$19.99</h2>
            <p class="product__description">
              A very interesting book about so many even more interesting
              things!
            </p>
          </div>
          <div class="card__actions">
            <button class="btn">Add to Cart</button>
          </div>
        </article>
        <% } %>
      </div>
      <% } else { %>
      <h1>No Products Found</h1>
      <% } %>
    </main>
  <%- include('includes/end.ejs') %>

Open in new window


products.js (model)

static fetchAll() {
    const p = path.join(
      path.dirname(process.mainModule.filename),
      "data",
      "products.json"
    );
    fs.readFile(p, (err, fileContent) => {
      if (err) {
        return [];
      }
      return (JSON.parse(fileContent));
    });
  }

Open in new window


When you first run this code, you get an error message that says, "Cannot read property 'length' of undefined." The moderator then goes on to explain that there's a flaw in the "products.js" model file with the "fetchAll" method. He rattles off a bunch of terms and concepts that I'm struggling to understand and this is the substance of my question.

He explains that this code:

static fetchAll() {
    const p = path.join(
      path.dirname(process.mainModule.filename),
      "data",
      "products.json"
    );
    fs.readFile(p, (err, fileContent) => {
      if (err) {
        return [];
      }
      return (JSON.parse(fileContent));
    });
  }

Open in new window


...is going to be a problem because the "inner function" (fs.readFile) is going to be...

"...registered as a callback in the Event Emitter Registry, but then it just finishes with this function (referring to the entire "fetchAll" function) and this function itself does not return anything."

"The return statements that correspond to the inner function, belong to the inner function and not to the outer function. So 'fetchAll' doesn't return anything."

I understand what an "inner function" is and what an "Event Emitter Registry" is, but I don't understand what he's referring to in this context.

Why does "fetchAll" come back empty?

What does he mean when he says, "The return statements that correspond to the inner function belong to the inner function and not to the outer function?"

The "corrected" code looks like this:

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


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

What  did go wrong?


Thank you,

Iwan
0
Here's my code:

const fs = require("fs");
const path = require("path");

module.exports = class Product {
  constructor(t) {
    this.title = t;
  }

  save() {
    const p = path.join(
      path.dirname(process.mainModule.filename),
      "data",
      "products.json"
    );
    fs.readFile(p, (err, fileContent) => {
      let products = [];
      if (!err) {
        products = JSON.parse(fileContent);
      }
      products.push(this);
      fs.writeFile(p, JSON.stringify(products), err => {
        console.log(err);
      });
    });
  }

  static fetchAll() {
    return products;
  }
};

Open in new window


The error that I'm getting is:

SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at fs.readFile (C:\wamp\www\adm\node\express_tutorial\models\product.js:18:25)
    at FSReqWrap.readFileAfterClose [as oncomplete] (internal/fs/read_file_context.js:53:3)
[nodemon] app crashed - waiting for file changes before starting...

This is line #18: products = JSON.parse(fileContent);

Two questions: First of all, what am I missing that would result in the error that I'm getting?

Secondly, what is "18:25?" I'm referring to the actual error message. "18," I'm assuming, is line #18, but what is "25?"

Thanks!
0
I'm working through a tutorial on Node where I've got an MCV architecture going on.

This is the relevant piece of my Controller:

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

exports.postAddProduct = (req, res, next) => {
  const product = new Product(req.body.title); // right here I'm establishing a new instance of my Product class and I'm passing a variable into that class that's coming from my form
  product.save();
  res.redirect("/");
};

Open in new window


This is the relevant portion of my Model:

const products = [];

module.exports = class Product {
  constructor(title) {
    this.title = title;
  }

  save() {
    products.push(this);
  }

Open in new window


What you see works and there's nothing about it that's especially confusing, but I did have a question.

When I saw this syntax, I was able to understand its logic based on my experience with PHP, as far as creating an instance of a class and having a constructor sitting at the top of that class.

All good.

But that I started looking at it a little bit closer and noticed that I was passing a variable into a class.

You don't do that with PHP do you?

I know that's a bizarre question, but when I think of constructors in PHP, I'm thinking of defining some properties and the attaching values to those properties that I can then access throughout my class depending on their visibility.

But do you  / can you pass variables into a class in PHP?

There you go! A random question to kick off your Thursday morning...
0
I'm looking for some good learning resources for Json and Java to shorten some tasks.  Also looking for something on Node and Java.  Any suggested books or websites to learn this stuff?  By the way what application does Json and Node have?


Thanks!
0
Upgrade from VCSA 6.5 U1 to VCSA 6.7U1  done in HA mode but with warning
VCHA Upgrade is done but some details required to automatically create clones for Passive and Witness nodes could not be fetched. Delete the source Passive and Witness VMs and make two new clones of the upgraded Active node that will serve as new Passive and Witness VMs. VCHA Cluster should be set to Enabled after Passive and Witness join the cluster. Check documentation for configuring VCHA cluster manually.
Does anyone have additional information about this?
Thank you
0
Looking for examples of modern distributed web applications.

Hello all,

I am trying to understand some examples of complex modern web applications which are used in companies like Kroger , Office Depot or financial companies like Freddie Mac , Fannie Mae etc.

If someone wants to one day get ready to work in these companies as a junior / senior programming what all things they should know

this is a very broad question but some answers will help me ask some more targetted specific questions

I am very interested in learning about designing and making Enterprise Applications

thanks
-anshu
1
I am trying to deploy my first Node.js site to a live server (shared hosting) and I am at the point where I am trying to run npm start in terminal as I have installed all necessary npm packages and uploaded all relevant files. When it starts the process it looks like it's going to work but then after a while I get an error regarding a database connection timeout.

Error connecting to db: failed to connect to server on first connect [MongoNetworkError: connect ETIMEDOUT] Failed at the start script.

I tried it again locally and it worked fine so the issue isn't my login credentials or IP address as I set mongodb to allow all IP addresses to connect.

In my package.json file I have the db details like so:

 "scripts": {
    "start": "NODE_ENV=production MONGO_USER=myuser MONGO_PASSWORD=mypassword MONGO_DEFAULT_DATABASE=mydatabase node app.js",
    "start-server": "node app.js",
    "start:dev": "nodemon app.js"
  },

I will move them out of there and make the connection more secure with something like dotenv but for now I just want to get it working.

Any suggestions or ideas would be welcome!
0
Getting my Angular 4 application running again on my MacBook

I have not run this app for months and also upgraded my MacOS to Mojave weeks ago. And now I need to run my Angular 4 program from Visual Studio Code.

I have forgotten exactly how to force it into debug mode. Or, even run without debugging mode. I need to test if it still works.

How can I do this?

I assume I need to open Terminal and start the Node Angular server. How do I do this?

Thanks.
0
I want to build a http REST service in node js. I have few Javascript files.

how can i call the different functions in these different javascript files, from say one server.js file that I write in node js for the REST service?
0
Here is a part of my code:

if (url === "/message" && method === "POST") {
    const body = [];
    req.on("data", chunk => {
      console.log(chunk);
      body.push(chunk);
    });
     [b]req.on("end", () => {[/b]
      const parsedBody = Buffer.concat(body).toString();
      const message = parsedBody.split("=")[1];
      fs.writeFile("message.txt", message, err => {
        res.statusCode = 302;
        res.setHeader("Location", "/");
        return res.end();
      });
    });
  }
  res.setHeader("Content", "text/html");
  res.write("<html");
  res.write("<head><title>My First Page</title></head>");
  res.write("<body><h1>Yo, dog!</h1></body>");
  res.write("</html>");
  res.end();
});

Open in new window


This is what I understand: The order in which this code is being fired is:

req.on("end", () => { -> Event Listener is registered, but not triggered until the end of the overall process

res.setHeader("Content", "text/html"); -> this will fire before the "req.on" because while "req.on" is seen by the process, it's fired asyncronously so it's not processed until the very end.

That's going to be a problem in the the headers have already been set, which result in an error.

However, if I do this:

return req.on("end", () => { - then I don't get an error and the code runs fine.

Why? What's significant about "return" that it allows the code to run in a healthy manner? It seems like it's still and Event Listener and, as far as the Call Stack, it's not being fired until the end and I would expect the same error. But there is no error and I want to understand why.

What do you think?
0

Node.js

243

Solutions

360

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
>