Node.js

203

Solutions

335

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'm using MongoDBStore to store my session values which include my user object.

The tutorial I'm going through has the session document looking like this:

screenshot of session doc
Notice how the user object contains the "_id" field.

My current project, as far as the session collection is concerned, looks like this:

screenshot of no _id
I can't figure out why the "_id" field isn't being added to the "sessions" table.

I'm new to Node, so I'm not altogether certain what files you would need to see in order to effectively troubleshoot this puppy, but let me start with my app.js file and several others.

Thanks in advance for your help!

app.js :

const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const csrf = require("csurf");
const flash = require("connect-flash");

const errorController = require("./controllers/error");
const User = require("./models/user");

const MONGODB_URI =
    "mongodb+srv://username:password@somewhere.mongodb.net/landing_pages";

const app = express();

const store = new MongoDBStore({
    uri: MONGODB_URI,
    collection: "sessions"
});
const csrfProtection = csrf();

app.set("view engine", "ejs");
app.set("views", "views");

const startRoutes = require("./routes/start");
const authRoutes = require("./routes/auth");

Open in new window

0
Your Guide to Achieving IT Business Success
Your Guide to Achieving IT Business Success

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

What is the best way to access an MS Access Table within an MS SQL Server? I know how I could use an MS SQL Table within MS Access, but I need it the other way around.

What we like to do; there is an MS SQL Server we access existing tables by node.js. We would need some data from MS Access joined by MS SQL Tables in views.
0
I need a simple example of reading and parsing a text file in Node.JS.
We have some code to hack but no experience in the language.
It would be a very small file - with only around 7 parameters to read. These the would be displayed through the GUI.
I'm not sure if it'll need to be need need to be asynchronous yet.
1
Hi there,

Is there a way we could convert a VMware VM CD-ROM in vCenter from SATA to IDE without downtime? If there is, how should we do this as it restricted us to update from the GUI. Thinking if we could do this from the command line  converting the affected virtual machine CD-ROM virtual device node from SATA to IDE on the fly without shutdown BUT no idea how to do this.

Any help is GREATLY appreciated.

Thanks and regards,

Jun
0
This may be more a matter of taste rather than a technical question:

I have a web app that I'm going to be selling Membership access to. I'd like to use Shopify as the Merchant Account/Gateway in which I will need to purchase and configure two plugins:

1. A Recurring Subscription plug-in that will allow me to charge Customer's 30 days out from when they subscribed and keep that payment recurring for a given duration
and
2. An "Affiliate" plug-in as I will be paying a Sales Team a portion of the initial cost from the Customers.

I realize this is a big ask and I'm fairly new to Shopify, so please use laymen's terms with your suggestions. The app is written in Node.JS/React so I suspect that integration won't be too difficult for the Devs.

Thanks for your assistance.
0
Hi
Node.js
Calling the library https://github.com/naptha/tesseract.js#tesseractjs

We call the function worker.recognize(path2png, language) for OCR of a PNG in a await function.

async function readPNG(path2png, language) {
 const worker = new TesseractWorker();
 try{
   let result = await worker.recognize(path2png, language);
    return result.text;
 } catch (error) {
   console.error("************************** error=",error)
 } 
}

Open in new window


There is a crash in tesseract and we would expect that it lands in the catch(error), but it does not. Instead, we get this and no callback.

contains_unichar_id(unichar_id):Error:Assert failed:in file /src/src/ccutil/unicharset.h, line 502
trap!
trap!
abort("trap!"). Build with -s ASSERTIONS=1 for more info.
abort("trap!"). Build with -s ASSERTIONS=1 for more info.

/home/diego/NetBeansProjects/FromGitHub/tmp/localsearch_triage/node_modules/tesseract.js-core/tesseract-core.js:8
var Module=typeof TesseractCoreWASM!=="undefined"?TesseractCoreWASM:{};var moduleOverrides={};var key;for(key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}Module["arguments"]=[];Module["thisProgram"]="./this.program";Module["quit"]=(function(status,toThrow){throw toThrow});Module["preRun"]=[];Module["postRun"]=[];var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof 

Open in new window

0
I'm looking for a macro to help to me count and display direct and indirect subordinates in Visio Org Charts. I found the sample one online below, but I running into issues with the
"s.Shapes(4).Text = dc" portion.

Function RecursiveCount(s As Shape) As String
    Dim count As Integer
    
    count = 0
    dc = s.FromConnects.count - 1
    
    For i = 1 To s.FromConnects.count
       If s.Text <> s.FromConnects(i).FromSheet.Connects(2).ToSheet.Text Then
            count = count + 1
            rc = RecursiveCount(s.FromConnects(i).FromSheet.Connects(2).ToSheet)
            count = count + rc
       End If
    Next
    If dc > 0 Then
        s.Shapes(4).Text = dc
        If (count > 0) And (count <> dc) Then
            s.Shapes(4).Text = s.Shapes(4).Text & "(" & count & ")"
        End If
    End If
    RecursiveCount = count
End Function
 
Sub CountSubs()
    ' select the top most node then run this macro
    Dim s As Shape
    Set s = ActiveWindow.Selection(1)
    
    ' now recursively update counts
    i = RecursiveCount(s)
    
End Sub
 
Sub SetCountsToBlank()
Dim s As Shape
For Each s In ActivePage.Shapes
        If s.Shapes.count >= 4 Then
            s.Shapes(3).Text = ""
            s.Shapes(4).Text = ""
    
        End If
    Next
End Sub

Open in new window

0
Am I explaining this function correctly? Am I using the right terms and logic?

Here's my method:

addOrder() {
❶ const db = getDb();
② return this.getCart()
  .then(products => {
	const order = {
	  items: products,
	  user: {
		_id: new ObjectId(this._id),
		name: this.name,
		email: this.email
	  }
	};
	❸ return db.collection("orders").insertOne(order);
  })
  ❹ .then(result => {
	this.cart = { items: [] };
	return db
	  .collection("users")
	  .updateOne(
		{ _id: new ObjectId(this._id) },
		{ $set: { cart: { items: [] } } }
	  );
  });
}

Open in new window


I want to be able to understand this, not just in terms of its logical flow, but also in the theory behind it so I can explain it to others...

Here's what I've got. Let me know if I've nailed it or I need to tweak my understanding.


① I'm establishing my database connection

② you'll need to return the result of the "then" block so your controller has a result to publish. That part of the Controller looks like this:

exports.getOrders = (req, res, next) => {
  req.user
    .getOrders()
    .then(orders => {
      res.render("shop/orders", {
        path: "/orders",
        pageTitle: "Your Orders",
        orders: orders
      });
    })
    .catch(err => console.log(err));
};

In addition, the result of the "getCart" is going to be all of the data that's coming from the "getCart" method which includes the productId and the quantity. You'll throw that in the "items" object and then …
0
When I try to start coding a new Angular app using  "ng new myFirstApp", I am getting the error:

-bash: /Users/jlpereira/.npm-global/bin/ng: No such file or directory

can anyone help?
0
Hi Experts,

I am working on reactJs(redux and redux thunk) application on front-end and django and nodejs on the back end.  I have a question.  I would like to know, how to reset the state (redux) to the initial state in the middle of the application.  Can anyone provide me with an idea of how to do this?

Thanks
0
OWASP: Avoiding Hacker Tricks
LVL 13
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Hi Experts,

I am working on an application with Reactjs as front end (Redux , redux thunk, reactjs) and django and nodejs on backend,  I get the following runtime error

 Unhandled Rejection at: Promise {
[1]   <rejected> TypeError: Cannot read property 'facets' of undefined
[1]     at searchComplete (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/search/static/search/reducers/search.js:140:59)
[1]     at search (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/search/static/search/reducers/search.js:246:14)
[1]     at combination (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/redux/lib/combineReducers.js:133:29)
[1]     at dispatch (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/redux/lib/createStore.js:178:22)
[1]     at /home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/redux-thunk/lib/index.js:14:16
[1]     at /home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/react-router-redux/middleware.js:18:18
[1]     at dispatch (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/redux/lib/applyMiddleware.js:45:18)
[1]     at _callee$ (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/search/static/search/actions/search.js:171:15)
[1]     at tryCatch (/home/ubuntu/workarea/sourcecode/ntdl/ntdl/ntdl-2/node_modules/babel-cli/node_modules/regenerator-runtime/runtime.js:65:40)
[1]     at Generator.invoke [as _invoke] 

Open in new window

0
const mongodb = require("mongodb");
const MongoClient = mongodb.MongoClient;

const mongoConnect = callback => {
  MongoClient.connect(
    "mongodb+srv://brucegust:Mu5cular!@brucegust-qhxnz.mongodb.net/test?retryWrites=true"
  )
    .then(client => {
      console.log("Connected");
      callback(client);
    })
    .catch(err => {
      console.log(err);
    });
};

mongoConnect(client => {
  console.log(client);
  app.listen(3000);
});

Open in new window


Am I explaining what I have above correctly...?

"mongoClient" is a constant that "houses" the functionality documented on lines 4-15. We trigger that functionality by referencing the mongoConnect constant on line 17. We pass an anonymous function as an argument to the mongoClient function which is going to be represented by the word "callback" which you can see on line four.

The mongoClient function is actually a "promise" which gives us the opportunity to structure an "IF / ELSE" scenario based on the successful completion of a callback. In this case, the callback that we're most interested in is on line 5-6 where we're grabbing the "mongoClient" and connecting to the database. If that callback happens successfuly, we proceed to the "then" block. As per the way "promises" are structured, we have access to the result of the successful callback as a variable which, in this case, we are calling "client." The "client" variable, which is a successful connection to the database, is passed to the callback which is then going to document the details of that connection (line #18) and we're also going to see "connected" in the console thanks to line #9.

Is that right?
0
In a file I have data that looks like this:

id=1349 console.log('done this') status=waiting
id=2345 console.log('done this too') status=waiting

Open in new window


If will read a line at the time, then change status to complete and save it back to the file.

So this is what I've got:

fs.readFile('list.txt', 'utf8', function (err,data) {

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

    const str = data.trim();
    const arr = str.replace(/;$/gm, '').split(/\n/g)

    for (var i = 0; i < arr.length; i++) {

      var result = arr[i].replace('status=waiting', 'status=complete');

      var temp = result.split(" ");
      console.log(temp[1]);
      eval(temp[1]); //run the console.log

      console.log(`RESULT IS: ${result}`); // This line should now have status=complete when it saves below

      // Now Save it back with the status=complete in it
      fs.writeFile('list.txt', result, 'utf8', function (err) {
        if (err) return console.log(err);
      });
      

    };


  }

});

Open in new window


The problem is the saving... Although variable result is correct before saving, it's just replacing the file text and only saving the last one.

How can I fix this?

ps: I know eval shouldn't be used but this is just for personal use.
0
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
Get Blueprints for Increased Customer Retention
Get Blueprints for Increased Customer Retention

The IT Service Excellence Tool Kit has best practices to keep your clients happy and business booming. Inside, you’ll find everything you need to increase client satisfaction and retention, become more competitive, and increase your overall success.

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

Node.js

203

Solutions

335

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.