Node.js

109

Solutions

206

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 writing a proxy app in nodejs which handles thousands of concurrent connections inwards and outwards, I want to make sure all idle and unneeded and ... connections get closed properly and their file descriptors get released. If it leaks file descriptors, I would run out of them very fast. my question is that what is the best solution to make sure a connection gets closed ? socket.end() or socket.destroy() ? currently I am using socket.end() but in doc it says it half closes the connection, is there a situation that socket.end() doesnt result in closing a connection ? what I am interested in is releasing the file descriptors ASAP. So what do you suggest ?
0
Turn Raw Data into a Real Career
Turn Raw Data into a Real Career

There’s a growing demand for qualified analysts who can make sense of Big Data. With an MS in Data Analytics, you can become the data mining, management, mapping, and munging expert that today’s leading corporations desperately need.

When I am trying to secure the users API; I am getting always 401 unauthorized. I have tried different variations to define strategy; but no luck. I have been using JWTStrategy and using jwtwebtoken while signing the token with the Secret and RS256 Algorithm

Passport.js

// import * as module from 'module';
const
  User = require('../models/user'),
  JwtStrategy = require('passport-jwt').Strategy,
  ExtractJwt = require('passport-jwt').ExtractJwt,
  config = require('./appconfig');

// Setting JWT strategy options
const jwtOptions = {
  // Telling Passport to check authorization headers for JWT
  jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
  // Telling Passport where to find the secret
  secretOrKey: config.jwtSecret,
  algorithms:['RS256']
  // TO-DO: Add issuer and audience checks
};

console.log(config.jwtSecret);
module.exports = function(passport) {
  passport.use(new JwtStrategy(jwtOptions, function(jwt_payload, done) {
    console.log(jwt_payload);
    User.findOne({id: jwt_payload.sub}, function(err, user) {
      if (err) {
          return done(err, false);
      }
      if (user) {
          return done(null, user);
      } else {
          return done(null, false);
          // or you could create a new account
      }
    });
  }));
};

Open in new window

Index.Route.js
const express = require('express');
const userRoutes = require('./user.route');
const authRoutes = require('./auth.route');
// const postRoutes = require('./post.route');
const passport = require('passport');


passport.initialize();
var jwt = require('../config/passport')(passport);

const router = express.Router(); // eslint-disable-line new-cap

/** GET /health-check - Check service health */
router.get('/health-check', (req, res) =>
  res.send('OK')
);

// mount user routes at /users
router.use('/users', passport.authenticate('jwt', { session: false }), userRoutes);

// mount auth routes at /auth
router.use('/auth', authRoutes);

// router.use('/posts', postRoutes);

module.exports =  router;

Open in new window

Using Postman: Header: Authentication: JWT Token

localhost:4040/api/users
0
I am unable to install nodejs on Solaris-10 x86 server. It is complaining about some libraries . Can somebody guide on this ?
-bash-3.2# cat /etc/release
                    Oracle Solaris 10 1/13 s10x_u11wos_24a X86
  Copyright (c) 1983, 2013, Oracle and/or its affiliates. All rights reserved.
                            Assembled 17 January 2013
-bash-3.2# pwd
/var/tmp/node-v8.11.2-sunos-x64/bin
-bash-3.2# ./node
ld.so.1: node: fatal: libsocket.so.1: version 'SUNW_1.7' not found (required by file node)
ld.so.1: node: fatal: libsocket.so.1: open failed: No such file or directory
Killed
-bash-3.2# ldd node
        libkstat.so.1 =>         /lib/64/libkstat.so.1
        libumem.so.1 =>  /lib/64/libumem.so.1
        libsocket.so.1 =>        /lib/64/libsocket.so.1
        libsocket.so.1 (SUNW_1.7) =>     (version not found)
        libnsl.so.1 =>   /lib/64/libnsl.so.1
        libsendfile.so.1 =>      /lib/64/libsendfile.so.1
        libstdc++.so.6 =>        (file not found)
        libm.so.2 =>     /lib/64/libm.so.2
        librt.so.1 =>    /lib/64/librt.so.1
        libgcc_s.so.1 =>         (file not found)
        libpthread.so.1 =>       /lib/64/libpthread.so.1
        libc.so.1 =>     /lib/64/libc.so.1
        libc.so.1 (ILLUMOS_0.17) =>      (version not found)
        libc.so.1 (ILLUMOS_0.8) =>       (version not found)
        libmp.so.2 =>    /lib/64/libmp.so.2
        libmd.so.1 =>    /lib/64/libmd.so.1
        libscf.so.1 =>   /lib/64/libscf.so.1
        

Open in new window

0
Hi EE,

At the moment, I'm hosting my website on Heroku, and have come about a very frustrating issue I don't know how to approach.

My app uses React.js and Node.js -
In the index file (server.js), the following logic is used:

const express = require('express');
const fs = require('fs');
const path = require('path');

var app = express();
var PORT = process.env.PORT || 3001;

if ( process.env.NODE_ENV === "production" ) {
  app.get( '/*',  function ( req, res )  {
    app.use(  express.static("client/build")  );//This is the index.html that was build with React
  });
};

app.listen(PORT, ()=>console.log('listening on port ' + PORT))

Open in new window


What the code does :
If we are in production, grab the build that was made in React.js and render it.

Here comes the problem..

When on the homepage,(  `/` )it renders perfectly.
But when we try to go somewhere like `about` or `contact`, Heroku will give me an error, because it thinks I'm making a request to the back end.

The React routing looks something like this:
class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <Switch>
        <Route exact path='/' component={Landing}/>
        <Route path='/blogs' component={Blogs}/>
        <Route path='/blog' component={Blog}/>
        <Route path='/contact' component={Contact}/>

        <Route path="/ping" component={Pong} />
        </Switch>
      </BrowserRouter>
    );
  }
}

Open in new window


Any insights into dealing with this deadly bug are greatly appreciated
0
I am trying to setup Mongoose and when I run NPM start I get the following error


Error: Cannot find module '.routes/users'
    at Function.Module._resolveFilename (module.js:547:15)
    at Function.Module._load (module.js:474:25)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/leotyndall/Desktop/node/nodeexpress/nodewebapp/app.js:12:13)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/leotyndall/Desktop/node/nodeexpress/nodewebapp/bin/www:7:11)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! nodewebapp@0.0.0 start: `node ./bin/www`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the nodewebapp@0.0.0 start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

i do have a folder with the routes/ see the file uploaded

I am lost why it wont run
0
I'm having difficulty putting a complex(to me) aggregation query together for my data. Basically, here's the run down so everyone understands my conundrum.

I have two collections in this equation. "training_documents" and "users". Each user object has a key identified by name "trainings" which is an array of objects. Each object within this trainings array, contains 4 key/value pairs. An example of each object is below.

    {
    	"document": ObjectId('5a0350ad7df0977d94cffab6'),
    	"trainee": ObjectId('59e51a4b7df0977d94cff95d'),
    	"trainer": ObjectId('595fcc2e04cf707693257890'),
    	"completion_time": "2018-04-23T21:28:22.747Z"
    }

Open in new window


The users trainings array will contain many objects following the aforementioned format.

An example user data structure is below for reference.

   
 [
    	{
    		"_id": "5ad782283c55b056bcc39e3z",
    		"site": {
    			"site_id": "site1",
    			"site_name": "Site One"
    		},
    		"user_name": "jsmith",
    		"first_name": "John",
    		"middle_name": "A",
    		"last_name": "Smith",
    		"full_name": "John Smith",
    		"title": "Duh Boss...",
    		"email": "testuser@example.com",
    		"last_login": "2018-04-27T14:27:27.014Z",
    		"type": "full-time",
    		"active": true,
    		"__v": 0,
    		"badge_id": "000001780343232123",
    		"trainings": [
    			{
    				"document": ObjectId('5ae33622a766885a121b7362'),
    				"trainee": 

Open in new window

0
I'm trying to copy from table from one table to another. So i want to stream the large data in and as it comes in I want to copy the contents of that data to another table. Its more then just a straight copy. I will probably massage the data a bit and then copy it over to the new table. The problem that I'm having is that row event keeps firing and I can't control it. I tried using async and await where I was hoping to make it stop but does not seem to be working. I can't control an event from firing or not. This is what I have so far. So basically I want to simulate a cursor in MSSQL. I don't want to download all the data and then do operations on it.

I'm not showing the massaging of the data below since I just want to see if I can copy data from one table to another.

var fs = require('fs');
var sql = require('mssql');
var sql2 = require('mssql');
var Request = require('tedious').Request; 
var TYPES = require('tedious').TYPES;  
var SqlString = require('sqlstring');

const config = {
    user: 'xxxx',
    password: 'xxx',
    server: 'xxxx\\',
    port: 'xxxx',
    database: 'xxxx',
    options: {
        instanceName: 'sql2014'
    }
};


function insertRecord(pool, record){
    return new Promise(function(resolve, reject){

        const request = pool.request();

        request.input('invoice_id', sql.Int, record.invoice_id);

        request.query('INSERT INTO _invoice_temp(invoice_id)  VALUES(@invoice_id)', (err, result) => {
            if(err){
          

Open in new window

0
Getting app.js:249 Service Worker Error TypeError: Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script. When trying to access the service worker using JavaScript. Need help ASAP. I can add my code if needed.
0
I've been though this tutorial to get electron to work on an angular 5 project.

As you can see it also installs ngx-electron module.

This has the following properties:

desktopCapturer: Electron.DesktopCapturer - Electron's desktop capturing API
ipcRenderer: Electron.IpcRenderer - Electron IpcRenderer
remote: Electron.Remote - Electron Remote capabilities
webFrame: Electron.WebFrame - Electron WebFrame
clipboard: Electron.Clipboard - Clipboard API
crashReporter: Electron.CrashReporter - Electron's CrashReporter
process: NodeJS.Process - Electron's Process Object
screen: Electron.Screen - Electron's Screen API
shell: Electron.Shell - Electron's Shell API
nativeImage: Electron.NativeImage - Electron's NativeImage API
isElectronApp: boolean - Indicates if app is being executed inside of electron or not


But I don't see how you can use FS ?

How can I use FS in this project with Angular 5 / Electron?
0
nodeJs and MongoDB
I Would like to  Create a dynamic navbar with mean stack a navbar that the admin can modify it navbar has
Main Categoy
Sub Categories title
sub category
example image https://prnt.sc/j3nxz7
0
Protect Your Employees from Wi-Fi Threats
LVL 1
Protect Your Employees from Wi-Fi Threats

As Wi-Fi growth and popularity continues to climb, not everyone understands the risks that come with connecting to public Wi-Fi or even offering Wi-Fi to employees, visitors and guests. Download the resource kit to make sure your safe wherever business takes you!

I'm currently working on a project in express and I'm using knex.js to handle migrations and queries.

I'm still trying to grasp the concept of promises and how I can run multiple queries with knex.

I have the following code which inserts a new record into my database, this is located in my `Unit model` file.

    this.addUnit = function(unit_prefixV, unit_nameV, unit_descriptionV, profile_id) {
             return new Promise(function(resolve, reject) {
                 knex.insert({ unit_prefix: unit_prefixV, unit_name: unit_nameV, unit_description: unit_descriptionV })
                    .into('units').then(function(unit) {
                        resolve(unit)
                    }).catch(function(error) {
                        reject(error)
                    })
             })
        }

Open in new window


In my `routes.js` file I then call this on a post request, like so:

    app.post('/dashboard/unit/add', ensureAuthenticated, function(req, res) {
            let postErrors = []
            if (req.body.unit_name.trim() == "") {
                postErrors.push('Unit name cannot be empty.')
            }
    
            if (req.body.unit_prefix.trim() == "") {
                postErrors.push('Unit prefix cannot be empty.')
            }
    
            if (req.body.unit_description.trim() == "") {
                postErrors.push('Unit description cannot be empty.')
            }
    
            if (postErrors.length > 0) {
                res.render('addUnit', { errors: postErrors, user: req.user })
            } else {
                unitModel.addUnit(req.body.unit_prefix.trim(), req.body.unit_name.trim(), req.body.unit_description.trim(), req.session.passport.user.id).then(function(unit) {
                    res.redirect('/dashboard')
                })
            }
        })

Open in new window


This successfully inserts a new record into my `units` table, however, I would like to select the user id from the users table with the matching `profile_id` and then insert another record into my `users_units` table. All within the `this.addUnit` function.

For reference my `users` table consists of:

  • - id
  • - google_id

my `users_units` table consists of:

  • - user_id
  • - unit_id

I've made an attempt to chain the queries but it only executed the initial insert query and not the others. Here is that rather ugly attempt:

Open in new window

0
Hi All,

This is my frist python script working on... I would like to list the servers or cluster from websphere. The script contents are below...
run by cmd - wsadmin.bat -lang jython -F listServers.py
Error -
WASX7209I: Connected to process "dmgr" on node dmgrNode using SOAP connector;  The type of process is: DeploymentManager
WASX7017E: Exception received while running file "listServers.py"; exception information: com.ibm.bsf.BSFException: exception from Jython:
Traceback (most recent call last):
  File "<string>", line 13, in <module>
ValueError: call stack is not deep enough

Content of the script - this example got from - C:\IBM\WebSphere\AppServer\scriptLibraries\servers\V70

#--------------------------------------------------------------------
# Set global constants
#--------------------------------------------------------------------
import sys
import java
import AdminUtilities

# Setting up Global Variable within this script
bundleName = "com.ibm.ws.scripting.resources.scriptLibraryMessage"
resourceBundle = AdminUtilities.getResourceBundle(bundleName)

# Retrieve scripting objects from local name space
AdminConfig = sys._getframe(1).f_locals['AdminConfig']
AdminApp = sys._getframe(1).f_locals['AdminApp']
AdminControl = sys._getframe(1).f_locals['AdminControl']
AdminTask = sys._getframe(1).f_locals['AdminTask']
Help = sys._getframe(1).f_locals['Help']    


## Example 1 List available servers with given server type and node ##
def …
0
execFile(script, (error1, stdout1, stderr1) => {
                        if (error1 || stderr1) {
                            logger.error(script);
                            logger.error("+++++++++++" + error1  );
                            reject(false);
                        }
                        if (stdout1) {
                            logger.info(script);
                            resolve(true);
                        }
                    });

Open in new window


when the script is log/getdata.bat
'log'is not recognized as an internal or external command, Pls suggest
0
Why does javascript node.js electron application throw uncaught  (in promise): error iat resolvePromise exception.
0
guys, here is the question. I have one function that optimize images using jimp package and I want to run this function on the command line of one server on digitalocean but i dont want to install lots of things on it. so I install npm and node, but I am very new to node and npm, so I dont know how to execute this javascript that will read the files and optimize images. I want to be able to do something like this on terminal:   execute optimize.js /var/www/html


here is the function I did:

function optimize(path){
    let Jimp     = require("jimp");
    let fs = Npm.require( 'fs' ),
    try { var files = fs.readdirSync(path); }
    catch(e) { console.log(e); }
    if (files.length > 0){
      for (var i = 0; i < files.length; i++) {
          //console.log(files[i]);
          var originalPath = path + '/original/' + files[i];
          var currentPath  = path + '/' + files[i];
          //copy img code here
          console.log('Processing 1. Copying bkp to folder: '+originalPath);
          fs.copyFileSync(currentPath, originalPath);
          //remove current file code here
          console.log('Processing 2. Removing current file from folder: '+currentPath);
          fs.unlinkSync(currentPath);
          //optimize image.
          Jimp.read(originalPath, function (err, lenna) {
                  console.log('Processing 3. Starting Optimizing from: '+originalPath);
                  console.log('Processing 4. Starting Optimizing to:   …
0
Created a duplicate username entry in mongoose database and resulted in duplicated error. Now everytime I start server, I get this error:

(node:14839) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): CastError: Cast to ObjectId failed for value "{ type: 'Buffer',
  data: [ 89, 243, 30, 231, 66, 69, 45, 56, 123, 65, 153, 72 ] }" at path "_id" for model "users"
(node:14839) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
0
I have a bunch of complicated node apis deployed on ec2s. What would be the easiest way to make them lambda compliant (by adding handler method) and deploy them on lambda ?
I am looking for some steps and guidance.
Thanks
0
Hi guys,

On our side we have a SAML2.0 SP implementation using simplesamlphp. Which works for dozens of customers. Including 5 ADFS customers.

But now we have one of the new integrations when things does not work. And it seems AD FS is not sending us required attributes. Customer claims that they as well have dozens of integrations and all of them work.

Their ADFS version is 3.0

Differences that we see between other responses (from successfull integrations with ADFS) and their response:
 
1.      There is no <status> xml node
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
</samlp:Status
<Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" ID="_36da30d0-467d-4eec-8dbd-f9da25545c61" IssueInstant="2017-08-09T12:42:00.977Z" Version="2.0">
2.      No Assertion node: <Assertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion" ID="_36da30d0-467d-4eec-8dbd-f9da25545c61" IssueInstant="2017-08-09T12:42:00.977Z" Version="2.0">
3.      No “<Subject>” node. The response ends with “<Signature>” xml node. And in other successfull implementations there is a “<Subject>” node which includes all the attributes (like uid, email and etc).

What could that be? They say, all claims are setup from their side.
0
Hi, I am using bootstrap treeview , I would like to know how I can add node dynamically at run time. means users should able to add any node.

any help will be highly appreciated.

Regards,

Aamir
addNodes.png
0
Get Cisco Certified in IT Security
Get Cisco Certified in IT Security

There’s a high demand for IT security experts and network administrators who can safeguard the data that individuals, corporations, and governments rely on every day. Pursue your B.S. in Network Operations and Security and gain the credentials you need for this high-growth field.

I am working with paypal payment. I want to implement payment condition below:-

Block payment amount on card at the time of reservation. If card cannot be blocked reject the event and add "Payment Declined" to the end of the description. Take payment at 12:01 am the day of the event.

For recurring events...
Block payment for first event at time of reservation. Take payment 12:01 am the day of the event.
For next event in the recurrence series, Block payment after the previous payment is taken and take payment at 12:01 am the day of the event. Continue this cycle until all reservations are complete.
 If card cannot be blocked reject the event and add "Payment Declined" to the end of the description but continue with the series of events.

Please know me how to implement.
0
Hi everyone i really need to know why i cant get to my EVO-rail manager for my vxrail. I have all my 4 nodes up and communicating i just cant get to the vxrail manager. Please help me.. the picture below show the 1st node which is shows that i have no vms.. what do i do? M i missing something ?
0
When I hit ng serve on cmd it's not working although its working 1st & 2nd time but its not working now. All things are running perfectly. eg ng --version .. the problem is only with ng serve ..it only runs for the 1st & 2nd time..

Here is the error that cmd geneartes.

 $ ng serve
    ENOENT: no such file or directory, stat 'E:\Work\Angular\Basic website\Angular 4\my-first-app\src\tsconfig.json'
    Error: ENOENT: no such file or directory, stat 'E:\Work\Angular\Basic website\Angular 4\my-first-app\src\tsconfig.json'
        at Error (native)
        at Object.fs.statSync (fs.js:1000:11)
        at AotPlugin._setupOptions (E:\Work\Angular\Basic website\Angular 4\my-first-app\node_modules\@ngtools\webpack\src\plugin.js:62:16)
        at new AotPlugin (E:\Work\Angular\Basic website\Angular 4\my-first-app\node_modules\@ngtools\webpack\src\plugin.js:27:14)
        at _createAotPlugin (E:\Work\Angular\Basic website\Angular 4\my-first-app\node_modules\@angular\cli\models\webpack-configs\typescript.js:55:12)
        at Object.exports.getNonAotConfig (E:\Work\Angular\Basic website\Angular 4\my-first-app\node_modules\@angular\cli\models\webpack-configs\typescript.js:71:19)
        at NgCliWebpackConfig.buildConfig (E:\Work\Angular\Basic website\Angular 4\my-first-app\node_modules\@angular\cli\models\webpack-config.js:29:37)
        at Class.run (E:\Work\Angular\Basic website\Angular 4\my-first-app\node_modules\@angular\cli\tasks\serve.js:43:98)
        at 

Open in new window

0
I have some cluster warnings after running the cluster validation wizard in my test environment on Virtual box Environment.
I have 2 Server (SQL-E and SQL-F) and 1 Domain Controller Server I should able to ping each other:
node1 -
10.10.10.50

node 2
10.10.10.60

both nodes connected to DC server(10.10.10.10 = iscsi target which is Domain controller Server)
When I validate to create the cluster. Now i receive 2 warning:
validate ip configuration
validate network communication
Going to "validate ip configuration" i see on both nodes a Local Area Connection 11 with an APIPA 169 address but looking on both servers i don't see this Local Area Connection 11 in network sharing center.
QUESTION1: How do i solve the below Error?
Going to "validate network communication" i see the warning below:
--node1 and node2 are connected by one or more communication paths that use disabled network. These paths will not be used for cluster communication and will be ignored. This is because interfaces on these networks are connected to an iscsi target. Consider adding additional network to the cluster, or change the role of on or more cluster networks after the cluster has been created to ensure redundancy of cluster communication.
--the communication path between network interface node1-nic1 and network interface node2-nic1 is on a disabled network.

This is driving me mad and I tried to ping back and forth with all servers. i should be able to reach. I do not have any clue to …
0
What will be the omnirpt command to get the list of all tapes used for the backup of a node?
0
We have  hosted  a UI application using Node js on AWS Elastic beanstalk in production environment . Because of minimal 1 to 5 % 5XX errors the EC2 instances keep going into degrade and then warning state. This is happening for very few minutes time interval. After sometime EC2 instance goes into normal state.  How to configure the threshold for 5 xx error so that we cannot see the server into degrade or warning state.
Server_State.PNG
0

Node.js

109

Solutions

206

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
>