Node.js

123

Solutions

251

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

Want to setup ionic cordova on ubuntu 16.04  with nodejs8.4 , can anyone tell me how to do that.
I installed it but ionic info not showing cordova.
0
Newly released Acronis True Image 2019
Newly released Acronis True Image 2019

In announcing the release of the 15th Anniversary Edition of Acronis True Image 2019, the company revealed that its artificial intelligence-based anti-ransomware technology – stopped more than 200,000 ransomware attacks on 150,000 customers last year.

2016 clustered environment . Nodes A crashed after a Ms path so it was rebuilt from an image of node B. I did make sure my ip's are correct.  Now im not able to Ping the private Network. Able to Ping one way only. Can ping from no B to node a. Cannot ping from node a two node be. This is after a crash where I had to rebuild node a from an image of node be. I have reset all settings but this one still has me confused any ideas.
Pings x.x.0.2 on nobe b to node a x.x.0.3 works.
Not working
Ping x.x.0.3  to x.x.0.2
Even isolated ping by typing.
Ping X.x.0.3 -S x.x.0.2
Still not pinging private network (heartbeat)
1
Hi,

In node red, while i insert the - timestamp datatype its work perfectly. while try to select data with the time stamp, its display different time.

Data insert in mariadb ----> 2018-09-19 23:47:26

While select data
if (Device > 0)
    msg.topic ="Select DeviceId, Line, outPIN, count,Time FROM mytab LIMIT 1";

return msg;

Open in new window


While try pull data out of mariadb the data timestamp show --> 2018-09-19 00:20:00
1
Connection Error: No Mongos proxy available.

Environment: Node.js, MongoDB, Mongoose

Start.js
const mongoose = require('mongoose');


mongoose.connect(process.env.DATABASE,  { useNewUrlParser: true })
mongoose.Promise = global.Promise;
mongoose.connection
  .on('connected', () => {
    console.log(`Mongoose connection open on ${process.env.DATABASE}`);
  })
  .on('error', (err) => {
    console.log(`Connection error: ${err.message}`);
  });

.env file

DATABASE=mongodb://username:DBpassword@player-shard-00-00-1cmur.mongodb.net:27017,player-shard-00-01-1cmur.mongodb.net:27017,player-shard-00-02-1cmur.mongodb.net:27017
0
Any Zurb Foundation users on here? I am getting the below errors when opening Foundation.

Version info:

Git = v2.13.2

Node = v7.1.0

NPM = v3.10.10

Foundation-CLI = v2.2.5

----------------------------------------------------

1)      I open the console/CMD Prompt
2)      Try to run:
-      foundation –v (to check Foundation CLI version)
-      -or -
-      foundation new (to start a new project)
3)      Get the error


SyntaxError: Unexpected token function

    at Object.exports.runInThisContext(vm.js:78:16)

    at Module._compile (module.js:545:28)

    at Object.Module._extensions..js(module.js:582:10)

    at Module.load (module.js:490:32)

    at tryModuleLoad (module.js:449:12)

    at Function.Module._load(module.js:441:3)

    at Module.require (module.js:500:17)

    at require (internal/module.js:20:19)

    at Object.<anonymous>(C:\Users\*****\AppData\Roaming\npm\node_modules\foundation-cli\node_modules\terminal-kit\lib\termkit.js:53:26)

    at Module._compile (module.js:573:32)

---------------------------------------

In PATH = Git then NPM then Nodejs

‘foundation –v’  -or- ‘foundation new’ resultsin:

C:\Users\*****\AppData\Roaming\npm\node_modules\foundation-cli\node_modules\terminal-kit\lib\detectTerminal.js:179

exports.getParentTerminalInfo = async functiongetParentTerminalInfo( callback ) {

                                                                     ^^^^^^^^
0
I want to import starting from the root folder, not go several folders down.
How do I do that?

I come across this issue while trying to import a guestbook (like it's 1999) script for my homepage.

import MyGuestbook from '../../components/MyGuestbook.vue'

Open in new window

compiles.

import MyGuestbook from '/src/components/MyGuestbook.vue'

Open in new window

doesn't compile.

GuestBookPage.vue

    <template>
    <div>
        <MyGuestbook />
    </div>
    </template>
    
    <script>
    import MyGuestbook from '../../components/MyGuestbook.vue'
    
    export default {
      name: 'GuestbookPage',
      components: {
        MyGuestbook
      }
    };
    </script>

Open in new window


MyGuestbook.vue

     
<template>
      </div>
      </div>
    </template>
    
    <script src="non-editable-comments-v0.1.0.js"></script>
    <script>
      window.safeComments('CommentTitle', 'CommentTargetID');
    
      export default {
        name: 'MyGuestbook'
      };
    </script>

Open in new window


I understand that I need to use webpack, but my project uses neutrinojs/vue (Recommended for the type of project) in combination with webpack. I'm not familiar with either of them. So far adding a _webpack.config.js_ and changing the import line to `import MyGuestbook from '@/components/MyGuestbook.vue'` has not worked.

    module.exports = {
      resolve: {
        extensions: [
          '.js', '.vue', '.json'
        ],
        alias: {
          '@': resolve('src'),
          '@root': resolve('.')
        }
      }
    };

Open in new window


Nor has editing _.neutrinorc.js_

    module.exports = {
      use: [
        '@neutrinojs/standardjs',
        [
          '@neutrinojs/vue',
          {
            html: {
              title: 'MySite'
            }
          }
        ],
        '@neutrinojs/jest',
        (neutrino) => {
    	  neutrino.config.resolve.extensions
    	    .add('.js')
    	    .add('.json')
    	    .add('.vue');
    		
          neutrino.config.resolve.alias
          .set('@', 'src')
          .set('@root', '.');
    	}
      ]
    };

Open in new window


the error:


Open in new window

0
I am trying to retrieve the average value from a PostgreSQL database using a Sequelize ORM with React on the front end and running Node.js server.  My 'GET' request on the Node side retrieves all of the data from the PostgreSQL database so I know everything is wired up with React using the following code:

module.exports = function (db, app, bodyParser) {


    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));

    app.get('/survey_init', function(req, res, next) {
        db.answers.findAll({})
        .then(function (data) {

            res.send(data);
              })
          .catch(function (err) {
            return next(err);
          })
        });
        
    }

Open in new window


However, when I attempt to run an average on a specific column called 'conf_one' in my PostgreSQL database I get an error.  I will list the modified code (modified from code above) that is throwing the error here:

module.exports = function (db, app, bodyParser) {


    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));

    app.get('/survey_init', function(req, res, next) {
        db.answers.findAll({
          attributes: ['conf_one', [models.Sequelize.fn('AVG', models.Sequelize.col('conf_one')), 'conf_one_avg']]
        })
        .then(function (data) {

            res.send(data);
              })
          .catch(function (err) {
            return next(err);
          })
        });
        
    }

Open in new window



The error that I get with the code is the following error and I do not get the result of an average calculation.


Open in new window

0
Hi,

I have a task in AWS that is started by ECS. I have developed a Cloudformation script that creates the ECS cluster, service, task definitions and containers.

The EC2 instances (2 to begin with) are initiated and are healthy. ECS then creates the tasks on each EC2 instance. However, have 1 minute, the tasks are stopped by ECS and it tries to recreate it. I presume this is something to do with the scheduler on AWS and not getting a healthy check back.

It is a node app running on port 300 which is mapped to the container. If I login to the EC2 instance and do a simple curl 127.0.0.1:32XXX (host port) then I get "no reply from server". Ok so it is something wrong with the image or container.

However, if I launch my own container of the same image publishing the ports ("docker run -d -p 32810:3000 <image> yarn start") and then do curl 127.0.0.1:32810 then I get a response from the server.

I cannot figure out how to debug this as there are no logs with any errors. Anyway..(I created the one on port 32810) the image is the same in both. I can only figure it is something to do with what the ECS agent does when it boots a task.

48ccad832ad2        <image>   "yarn start"        9 seconds ago       Up 8 seconds        0.0.0.0:32831->3000/tcp   ecs-test-InterfaceCogTaskDefinition-1UE2FONT2RQU3-1-InterfaceCog-f092fec2d9d1e8a90300
36016de55b81        <image>   "yarn start"        23 minutes ago      Up 23 minutes       0.0.0.0:32810->3000/tcp   practical_banach

0
I have a 2 node DAG Exchange 2013 CU19.
I am trying to delete any email older than 1/1/2016 for a specific user, but no matter what I do, I get nothing from searchquery filtering.
I Have confirmed Roll group Membership for Discovery Management and Mailbox Import Export.
I tried every format of double and single quotes for the date, and could not find anything.
I then tried to remove something from my mailbox, and get the same thing.
I sent me an email with subject test, and can not find it either.

I have tried:
search-mailbox -identity ttaylor -searchquery subject:test -estimatresulteonly
search-mailbox ttaylor -searcquery subject:test -estiamateresultonly
search-mailbox -identity ttaylor -searchquery "subject:test" -estimatresulteonly
search-mailbox ttaylor -searcquery "subject:test" -estiamateresultonly

I always get the same output
RunspaceId       : 304008d0-fa23-40d9-8867-d6ea567d5b9c
Identity         : Domain/ou/Tim Taylor
TargetMailbox    :
Success          : False
TargetFolder     :
ResultItemsCount : 0
ResultItemsSize  : 0 B (0 bytes)

Any suggestions
0
I had this question after viewing Change a specific key value in app.config file with another value..

i have  a config file as below
<meeServices>
  <edmServers>
    <server name="EDMServer" description="EDMServer" username="" password="" integratedSecurity="true" />
  </edmServers>
  <rdmServers>
    <server name="EDMServer" description="EDMServer" username="" password="" integratedSecurity="true" />
  </rdmServers>
  <settings>
    <add name="ExposureSource" value="path" />
    <add name="DomainDatabase" value="Server=HeadNode;Initial Catalog=RMS_MEE_Data;Integrated Security=True;" />
    <add name="ResultsDatabase" value="Server=HeadNode;Initial Catalog=RMS_MEE_Results;Integrated Security=True;" />
    <add name="JobManagerService" value="url" />
    <add name="licensecode" value="code" />
    <add name="WhiteListedIPAddresses" value="*" />
  </settings>
</meeServices>

 in settings , i want to change the name which contains licensecode to newcode. how do i do this.

$ConfigFile = 'C:\Users\psman\Downloads\dev_qa.config'
## XML Node names and Attributes are CaSe SeNsItIvE!
$xml = [xml](Get-Content -Path $ConfigFile)

$xml.SelectSingleNode("meeservices/settings/add[@name='licensecode']").SetAttribute("name", "data1")

$xml.Save($ConfigFile)
0
Choose an Exciting Career in Cybersecurity
Choose an Exciting Career in Cybersecurity

Help prevent cyber-threats and provide solutions to safeguard our global digital economy. Earn your MS in Cybersecurity. WGU’s MSCSIA degree program was designed in collaboration with national intelligence organizations and IT industry leaders.

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
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
CompTIA Cloud+
LVL 12
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

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

Node.js

123

Solutions

251

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
>