Node.js

113

Solutions

230

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

Hello,
I am creating a basic user authentication using nodejs, express.js and Passport.js.
I follow this example and it kind of works for me:
https://github.com/passport/express-4.x-local-example/blob/master/server.js

BUT, I would like to modify this demo to not have routes and not a template engine (ejs)

I have a folder with a bunch of static html files I would like to protect.
admin/
         /login.html
         /page1.html
         /page2.html
         /page3.html

I would like to password protect access to all html file under admin using basic authentication, but without routes.

In other words, I would like to access wepage.com/page2.html or any other html page and be redirected to login page, after logging in, I would like to be redirected back to page2.html and after that I could access the rest of the html pages without having to login. wepage.com/page4.html, wepage.com/page3.html, etc

The reason I don't want to have routes is because new html pages are added all the time and I don't want to keep creating routes for new ones or remove routes when deleting html pages.
Also, I don't really need a template engine since my pages are static html and I would like people to access the html directly. wepage.com/page1.html

The only requirements I have is nodejs, express.js and Passport.js.

Can someone please guide me or point me to an example to accomplish this?

Thanks
EMimi
0
Cloud Class® Course: Certified Penetration Testing
LVL 12
Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

So i have a user schema like this:

var user_schema = new Schema({
   username:{type:String,required: true, unique : true, trim: true},
   college:{type:String,required: true},
   password:{type:String,required: true, trim: true},
   email:{type:String,required: true, unique : true, trim: true},
   phone:{type:Number,required: true, unique : true, trim: true},
   dp:{type:String},
   tag:{type:String},
   description:{type:String},
   friends:[{type:String}],
   pending:[{type:String}],
   skills:{type:String},
   bucket:[{type:String}]
  });

Open in new window

and my objective is, to search the all the documents in the collection to get people based on the following conditions:

1. They should not be in the users' "friends" array.
2. They should not be in the users' "pending" array.
3. They should have the same "tag" (a string value) as the user.

So, basically I have to compare the users' fields ("friends","pending" and "tags"), with fields of all documents in the whole collection.

How do I do it, using mongoose (nodejs mongodb library)
0
I have to initialize an array to [](empty array) and then push user chose "tags" into it. This is my schema:

 var user_schema = new Schema({
   username:{type:String,required: true, unique : true, trim: true},
   college:{type:String,required: true},
   password:{type:String,required: true, trim: true},
   email:{type:String,required: true, unique : true, trim: true},
   phone:{type:Number,required: true, unique : true, trim: true},
   dp:{type:String},
   tags:[{type:String}],
   description:{type:String},
   skills:{type:String},
   bucket:[{type:String}]
 }); 

Open in new window

` and i have to initialize "tags" to [] and push user string values (user entered/chosen) every time the request is made to the API call.

I am using this line of code:

 stu_user.findOneAndUpdate(
   { _id: req.decoded.id },
   { $set:{tags:[]},$push: { tags: 'some chosen string'  } },
  function (error, success) {
         if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });

Open in new window

But it's not working.
0
I'm a complete beginner so I may have made some stupid mistakes. I made this script with x-ray to scrape user's phone number pictures from different website pages. The script was working very well until it reaches a page where the user didn't put his number in the page and the script stops.

How can I make it continue to the next page even if the phone number doesn't exist? and is there a way to make the script save the pictures directly to my computer instead of giving me the links?
 const Xray = require('x-ray');
const requesst = require('request');
const fs = require('fs');

const xray = Xray()

xray('https://www.marocannonces.com/categorie/350/Appareils-photos,-caméscopes/annonce/6503723/Nikon-D40x-objectif-18-135mm.html', 'div.infoannonce', [{
	numero: '#phone_number img@src',
	nom: '.infoannonce dd',
}])

.paginate('a.next_ad_link@href')
.write('results.json'); 

Open in new window

0
i'm beginner to Node JS and javascript. Now everybody is saying to learn Node JS and javascript to develop a fastest, scalable and very good web application.

I thought of developing via Zk or Vaadin framework and experts says Node Js and javascript is far better than Zk or Vaadin

Could someone help with the thoughts and recommendation of which one to go and which one would be fast, reliable and scalable?

Like word press plugins, zk and vaadin components, Do we have a best java script framework which has huge components to integrate and create a beautiful and fastest responsive web app?

Thanks.
0
How to enable the movement of my html files in handlebars or .ejs? I have intended an html template in an .ejs file inside my node views and the slider does not move, another script that should move some numbers directly shows static without dynamism. How to solve this problem?



In my templating engine .ejs i can t see this 2 animations: (slider and animation numbers)

ejs slider

ejs animation
Hear is the code: https://github.com/casperverse/octoeffective/blob/tem/views/main/about.hbs

The slider and the animation numbers in html:

html slider and animation looks nice the move is great.

https://github.com/casperverse/octoeffective/blob/tem/public/about-us.html

I need use ejs this is the problem.
Somebody know how do this?
0
I have the google c# api code and it works fine.But I want to get
child node : photos {height and width}.
rating
open now
weekday text
viewport

Can you help me what I need to do with the codes below? Thank

reference: https://developers.google.com/places/web-service/search


       
protected void Page_Load(object sender, EventArgs e)
        {
             WebClient wc = new WebClient();
            string jsonStr = wc.DownloadString("https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=37.753,-122.443&radius=10000&type=rv_park&key=AIzaSyCietasdfasdfasdfasdfxzD65Uc19X6DgrJFumdi-nCZYSHjg");
            GooglePlacesResponse gpr = (GooglePlacesResponse)JsonConvert.DeserializeObject<GooglePlacesResponse>(jsonStr);
            Response.Write(gpr.status + "<br><br>");
            foreach (results r in gpr.results)
                {
                
                Response.Write
                    (r.name + " "  + 
                     r.geometry.location.lat + " " + 
                     r.geometry.location.lng + " " +
                     r.reference + " " +
                     r.vicinity  + " " +                         
                     "<br><br>");
            }

         } 
        public class GooglePlacesResponse
        {
            public string status { get; set; }
            public results[] results { get; set; }
        }
        public class results
        {
            public geometry geometry { get; set; }
            

Open in new window

0
I have a Node project written in TypeScript where the application takes in user's input arguments and does some calculation and prints out the results. Take the example of a calculator the user inputs value of two numbers and it prints out the addition of two numbers. for example npm run calc 3 5. The application prints out 8.

The application is working but i want to make this an aws lambda function and deploy it in aws. The examples i see everywhere is hello lambda function. Can anyone help me how i can make a handler and deploy it to aws?

How do i convert the below hello function to a calc lambda function and deploy it to aws?
export const hello: Handler = (event: APIGatewayEvent, context: Context, cb:             
Callback) => {
const response = {
statusCode: 200,
body: JSON.stringify({
message: 'Go Serverless Webpack (Typescript) v1.0! Your function executed 
successfully!',
  input: event,
}),
};

cb(null, response);
}

Open in new window


This is my addition class

export class Calc {
public static add(){

    console.log( this.addition( (process.argv[0] + process.argv[1] ));

}
public static addition(num1:number, num2:number)
{
    return num1 + num2;
}

Open in new window

0
Hi,

My manager asked me updating a website from codeigniter to  
backend: API using PHP (Symfony) or node (expressjs) or Drupal 8 . or any other framework. can you give me explanations?

And for single page applications Angular 4 or Vue js
0
Hey, This is just a decision-making problem. I am seeking for a well thought out answer.
I have to develop an android XMPP chat application, (the application also has a NodeJS server API, connecting to MongoDB and AWS S3 for picture uploads)

which will be better:

1. Having a "openfire" server on aws and connecting it to the android application and implementing an XMPP client on the android device using "smack" library.

2. Implementing a "xmpp-client" on NodeJS server side and scrape the results from this API to the Android device.
0
KuppingerCole Reviews AlgoSec in Executive Report
KuppingerCole Reviews AlgoSec in Executive Report

Leading analyst firm, KuppingerCole reviews AlgoSec's Security Policy Management Solution, and the security challenges faced by companies today in their Executive View report.

We had same issue but unable to find cause. it happened at random time.No logs from ESX host,network switch. looks it is not communicating internally.error :
Cluster network interface 'node-03 - VLAN 10' for cluster node 'node-03' on network 'Cluster Network 1' failed. Run the Validate a Configuration wizard to check your network configuration. If the condition persists, check for hardware or software errors related to the network adapter. Also check for failures in any other network components to which the node is connected such as hubs, switches, or bridges.
Please advise solution
0
i am trying to run

npm install mysql

command in cmd its giving me these error

npm ERR! Unexpected end of JSON input while parsing near '....tgz"},"engines":{"no'

npm ERR! A complete log of this run can be found in:

npm ERR! C:\Users\HP\AppData\Roaming\npm-cache\_logs\2018-05-30T06_49_09_337Z-debug.log
0
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
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
Making Bulk Changes to Active Directory
LVL 8
Making Bulk Changes to Active Directory

Watch this video to see how easy it is to make mass changes to Active Directory from an external text file without using complicated scripts.

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

Node.js

113

Solutions

230

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
>