Menu
  • HOME
  • TAGS

NodeJS child process stdout are all numbers

Tag: node.js,stdout,child-process

I'm writing some node.js scripts to kick off a child process. Code snippet is as below.

var spawn = require('child_process').spawn; 
var child = spawn ('node', ['script.js'])

child.stdout.on('data', 
    function (data) {
        logger.verbose('tail output: ' + JSON.stringify(data));
    }
);

child.stderr.on('data',
    function (data) {
        logger.error('err data: ' + data);
    }
);

Script runs well except that child process's stdout and stderr prints only numeric outputs:

Sample output:

   108,34,44,34,105,110,99,114,101,97,109,101,110,116,97,108,95,112,111,108,108,105

How do I convert these numeric values to readable string?

Thanks.

Best How To :

data is an array buffer. Call its toString method JSON.stringify(data.toString('utf8'))

Getting CROS Error even after adding header in node.js for Angular js

javascript,angularjs,node.js

The error message spells it out for you. Your client side code is trying to set an Access-Control-Allow-Origin header: RestangularProvider.setDefaultHeaders({"Access-Control-Allow- Origin":"*"}); Your server side code allows a number of headers, but that isn't one of them: 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept"', Remove the line: RestangularProvider.setDefaultHeaders({"Access-Control-Allow- Origin":"*"}); Access-Control-Allow-Origin is a response...

Getting failed to load c++ bson extension error using Mongodb and Node.js

javascript,node.js,mongodb

Since you're using the mongojs module, you're going to have to connect to the database using the following method db = mongo("127.0.0.1:27017/"+db, collections); ...

How to use promises to do series without duplicate code

node.js,promise,bluebird

Just use a loop. var lastPromise = Promise.resolve(); for (var x = 0; x < 100; x++) { lastPromise = lastPromise.then(function () { return object.asyncFunc(); }); } You could also use Promise.reduce over an array with a length of 100 to achieve the same effect. Promise.reduce(new Array(100), function () {...

How to add new items to an array in MongoDB

arrays,node.js,mongodb

$set is not an array update operation. The $set operator replaces the value of a field with the specified value. You just want to use $push by itself, as in .update({_id: id}, {$push: {name: item}}) You can't interpolate object property names in raw object declarations, so if you want to...

Threading script not printing to console

python,stdout,python-multithreading

According to the thread documentation, When the main thread exits, it is system defined whether the other threads survive. On SGI IRIX using the native thread implementation, they survive. On most other systems, they are killed without executing try ... finally clauses or executing object destructors. So it is most...

Why is address undefined in my app?

node.js,express,jasmine,supertest

request(app.app) instead of request(app) in integration test should fix the error. var request = require('supertest'); var app = require('../app'); describe('GET /', function(){ it('should repsond with 200', function(done){ request(app.app) .get('/') .expect(200, done.fail); }); }); ...

Sockets make no sense?

javascript,node.js,sockets

The client doesn't get to cause arbitrary events to fire on the socket. It is always a message event. Using the same client, try this server code in your connection handler: socket.on('message', function(data) { // data === "pressed", since that's what the client sent console.log("Pressed!"); socket.close(); }); ...

Socket.IO message doesn't update Angular variable

javascript,angularjs,node.js,sockets

You need to wrap the change of the model (changing properties on the $scope), with $scope.$apply(function() {}) in order to to update the view. var container = angular.module("AdminApp", []); container.controller("StatsController", function($scope) { var socket = io.connect(); socket.on('message', function (msg) { console.log(msg); $scope.$apply(function() { $scope.frontEnd = msg; }); }); }); $apply()...

What are some patterns I can look at for database implementations in JavaScript?

javascript,node.js,mongodb

That's a pretty wide question, partly opinion based. This question should be closed, but I still want to give you some advice. There once was the Active Record pattern, which has been proven to be pretty difficult to maintain. The solution was the DAO pattern, but this adds a lot...

NPM : how to just run post-install?

node.js,npm,package.json

You can run individual script entries using npm run SCRIPTNAME: $ npm run postinstall ...

Socket.io client does not connect to server

node.js,express,socket.io

I don't know if this is the only issue, but you're calling this: var io = require("socket.io").listen(app); before you assign the app variable so it is undefined. The request for this URL: http://localhost:3000/socket.io/?EIO=3&transport=polling&t=1434334401655-37 is how a socket.io connection starts so that is normal. The problem is that the socket.io listener...

“Arguments to path.resolve must be strings” when calling 'gitbook build' from a Git hook

node.js,git,gruntjs,githooks,gitbook

Some further consideration brought me to the right direction: Invoking a Git hook has a different login context than working on the server's command line. So running set > some-file in both contexts revealed significant differences in environment variables. Some experiments turned out that it was export HOME=/home/git that had...

NodeJS / ExpressJS check valid token parameter before routing

node.js,express,parameters

Use a middleware. app.use(function (req, res, next) { if (checkToken(req.query.token) { return next(); } res.status(403).end("invalid token"); }); app.use(require('./controllers')) ...

jQuery DataTables with Node.js

javascript,jquery,node.js,datatables,jquery-datatables

You need to define dataSrc and columns.data - the following should work : var table = $('#example').DataTable({ processing: true, serverSide: true, ajax: { url: "/viewreports", dataSrc: "reportList" }, columns: [ { data : "reportID" }, { data : "eBayUserID" }, { data : "reportStatus" }, { data : "summary" },...

React from NPM cannot be used on the client because 'development' is not defined. The bundle was generated from Webpack

javascript,node.js,npm,reactjs,webpack

Any values passed to webpack.DefinePlugin as strings are treated as code fragments—that is to say, using new webpack.DefinePlugin({ ENV: "development" }); with the code console.log(ENV); results in console.log(development); Instead, you want new webpack.DefinePlugin({ ENV: "\"development\"" }); which will result in console.log("development"); To fix your issue, change your plugins to plugins:...

nodejs head request isn't triggering events

node.js,http

The problem is that you don't declare a data or readable event handler. According to the fine manual: A Readable stream will not start emitting data until you indicate that you are ready to receive it. Instead, the stream will be put in a "paused" state indefinitely (until you start...

Replace nodejs for python?

python,node.js,webserver

You might want to have a look at Tornado. It is well-documented and features built-in support for WebSockets. If you want to steer clear of the Tornado-framework, there are several Python implementations of Socket.io. Good luck!...

Error handling when uploading file using multer with expressjs

node.js,express,multer,busboy

You can handle errors using the onError option: app.post('/upload',[ multer({ dest : './uploads/', onError : function(err, next) { console.log('error', err); next(err); } }), function(req, res) { res.status(204).end(); } ]); If you call next(err), your route handler (generating the 204) will be skipped and the error will be handled by Express....

With Sails.js how can I make /users/me a route that works with associations?

javascript,node.js,sails.js

The easiest way I can imagine doing this without setting findOne methods in each controller would be to create a policy that matches the /users/me/notifications route, redirecting it to the current session's user id. You could potentially use something like the following, and update the /config/policy file. if (session.authenticated) {...

What type of database is the best for storing array or object like data [on hold]

database,node.js,sockets

Redis would probably be fastest, especially if you don't need a durability guarantee - most of the game can be played out using Redis' in-memory datastore, which is probably gonna be faster than writing to any disk in the world. Perhaps periodically, you can write the "entire game" to disk....

How to block writes to standard output in java (System.out.println())

java,logging,stdout

If you can identify the thread you want to "mute" reliably somehow (e.g. by name), you can setOut to your own stream which will only delegate the calls to the actual System.out if they don't come from the muted thread.

mongodb populate method not working

node.js,mongodb,model,populate,auto-populate

When you create an instance of the Post model, you need to assign the _id from the user as an ObjectId, not a string: var ObjectId = require('mongoose').Types.ObjectId; Post.create({ text: 'farheen123', created_by: new ObjectId('5587bb520462367a17f242d2') }, function(err, post) { if(err) console.log("Farheen has got error"+err); else console.log(post); }); ...

javascript “this” keyword works as expected in browser but not in node.js

javascript,node.js

In both, the browser and Node, this inside the function refers to the global object (in this case). Every global variable is a property of the global object. The code works in the browser because the "default scope" is the global scope. var bar therefore declares a global variable, which...

How do I run C# within a Node.js server application?

c#,node.js,server

I have idea for your problem . U can write c# console app and then call it from nodejs . U can look this url Execute an exe file using node.js . after c# job writes all data to database, u can look to the this table read from it...

call functions in async with node which is more recomended Q or callback

javascript,node.js,callback,promise,q

I don't even see why you particularly need promises for this. function myHandler(req, res) { var dataChunks = [], dataRaw, data; req.on("data", function (chunk) { dataChunks.push(chunk); }); req.on("end", function () { dataRaw = Buffer.concat(dataChunks); data = dataRaw.toString(); console.log(data); var filePath = 'C://test.txt'; var writeStream = fs.createWriteStream(filePath, {flags: 'w'}); writeStream.write(data); writeStream.on('finish',...

Using TypeScript type definitions with Webstorm 10 [duplicate]

node.js,typescript,webstorm

Using that dialog, I downloaded the node and express type definitions and can see them in the External Libraries section of my project. However, I still get the same error about "require" That dialog gets TypeScript definitions to use with JavaScript. You need to download the typescript definitions manually...

I'd like to count the documents with the matching “name” property AND group them by “name” at the same time

node.js,mongoose,group-by

If you want mongodb to handle the query internally you could use the aggregation framework. In mongodb it looks like: db.users.aggregate( [{ $group: { _id: '$firstName', // similar to SQL group by, a field value for '_id' will be returned with the firstName values count: {$sum: 1} // creates a...

What does this line in NodeJs mean?

node.js

require returns what ever was defined in the package. In the cases above they are functions and so the second parameter is actually calling the function. If you break it out it would look like this: var debugFunctionFactory = require('debug'); var debug = debugFunctionFactory('morgan'); debug('this is a test debug command');...

Node Server - Source Code accessible

node.js,express

The obvious answer is to change the directory used in the express.static() middleware if you're using that. Typically there is a public or similarly-named directory that you would create that holds only your public assets. Remove the app.use(express.static(__dirname + '/'));, this is what is allowing your code to be public....

What does a [Function] (wrapped in square brackets) mean when inside of a javascript object?

javascript,node.js,javascript-objects

I'm able to replicate the output with the following setup: > function bar() {} > bar.baz = 42; > console.log({foo: bar}); { foo: { [Function: bar] baz: 42 } } So ObjectId: { [Function: ObjectId] schemaName: 'ObjectId' } } means that ObjectId is the property of an object. The value...

how can I import a file in node.js?

javascript,node.js

You will need to change this line: var template={ to this: module.exports={ And then you can simply do: var template = require('./path/to/template.js'); Note that this is a relative path to your file. You need to set module.exports because that is the convention NodeJS uses to say "this is what will...

websockets - reject a socket connection

node.js,sockets,websocket

You can either use socket.close() or socket.terminate() to close the connection.

hasMany relation: including from the other direction

node.js,strongloop,loopback

You have to define belongsTo relation in your Invoice model. invoice.json: {//... "relations":{ "receiver": { "type": "belongsTo", "model": "Receiver" }, } //... } Then you can query your model like this: Invoice.find({include: "receiver"}, function(data){ console.log(data); }); ...

Is there a before() function in Protractor?

angularjs,node.js,automated-tests,protractor,hierarchy

My solution to this problem was to split the two describe blocks in to 2 separate spec files. I figured this made more sense anyway, as each test had different conditions it needed to meet, and it isn't much hassle to have extra spec files.

Send code via post message is not working

javascript,node.js,express,postman

If you want to add a custom content type then you need to keep two things in mind: Content type couldn't be "application/text/enriched", in other hand "application/text-enriched" is ok. Max two "words". You must provide a custom accept header on body parser configuration BUT body parser return you a buffer...

Add multiple rows from same model AngularJS

angularjs,node.js

You should have an array of users in your controller and every time you press "Add another user" you can add a new user to your array. The code in your controller: $scope.users = [{ name: "1" , email: "email1", password:"pas1" }, { name: "2" , email: "email2", password:"pas2"}];; $scope.addUser...

Redis: Delete user token by email ( find Key by Value )

node.js,express,redis

You basically have to choose one of two approaches: a full scan of the database or an index. A full scan, as proposed in another answer to this question, will be quite inefficient - you'll go over your entire keyspace (or at least all the tokens) and will need to...

Access Node-Webkit App from other Application

node.js,node-webkit

I'm not familiarized with the applescript language, but is possible between languages that have an implemented library for socket.io Using socket.io you can behave between applications, socket.io act like an node.js EventEmitter (or pubsub), clients can send events and suscribe to those events in real-time. For your case you can...

Is express similar to grunt? what is the difference? what are the advantages of express over grunt?

node.js,express,gruntjs,mean-stack

Express is a webserver framework on top of nodejs (like symphony for php). Grunt is an automation tool (like make or gulp) and not a webserver. The only thing they have in common is, that they use the JavaScript programming language. MEAN is a full stack environment for developing web...

Error is not thrown inside a deferred method

node.js,exception-handling,deferred

The behavior of deferred seems reasonable to me in your cases. In the second case, I don't think that deferred has a way to catch the error thrown in the nextTick callback. So the error is thrown. In the first case, deferred catches it and considers that that resulting promise...

How to handle expressjs middleware request. post request remains pending made by dropzone

node.js,express,dropzone.js,multer

You need an Express route for your form post that will finish the http request. The multer middleware will process the file uploads and add them to the request so they are available to a route handler, but you need to have a route for the form post. From the...

How to use a variable as an Object Key [MongoDB] [duplicate]

node.js,mongodb

JavaScript has no nice notation for creating an object where the keys are variables: var $push_query = {}; $push_query[name] = item; ... {"$push": $push_query} ... ...

After deploying to heroky scripts and css not available

node.js,heroku

I resolved it. I think, I asked incorrect question. The problem was in missing bower command installation for dependencies when deploy.

How to get my node.js mocha test running?

javascript,node.js,mocha,supertest

Create a separate file called app.js. The only purpose of this file would be to run the server. You'll also need to export your app object from server.js. So, your server.js would look like this // set up ====================================================================== var express = require('express'); var app = express(); // create our...

Create n:m objects using json and sequelize?

javascript,json,node.js,sequelize.js

Have a look at nested creation (the feature is not documented yet) Store.create({ name:'corner store', address: '123 Main Street', products: [ { name: 'string beans' }, { name: 'coffee' }, { name: 'milk' } ] }, { include: [Product] }); This will create both stores and products and associate the...

node.js winston logger no colors with nohup

node.js,logging,nohup,winston

It's caused by colors package (used by winston) that performs the following check when trying to determine whether to support colors: if (process.stdout && !process.stdout.isTTY) { return false; } This means that when your application is running in a background, it doesn't have a terminal and colors are not used....

Waiting for promises - code hangs

javascript,node.js,promise

What you want is validate = function(data) { var p = new Promise(function(resolve, reject)){ var all_promises = Array(); all_promises.push(resBooking); resBooking.count(...).then(...).catch(...); Promise.all(all_promises).then(resolve); }); return p; }; In other words, call resolve, not p.resolve(). p.resolve will generate a run-time error (p doesn't exist), which will be "swallowed" by the promise constructor and...

Socket.IO server not receiving message from client

node.js,socket.io,mocha,bdd,expect.js

You need to change your code in two sides. First side, you will need to listen incoming socket connections on the socketIO object. (see the emphasized code below) //.. some code function Server(socketIO) { this.socketIO = socketIO; this.connectedUsers = {}; this.socketIO.on('connection', (function(user) { var userID = user.client.id; this.connectedUsers[userID] = user;...

node ssh2 shell unable to run apt-get install on remote machine

node.js

Try to change \nwith &&: stream.end('sudo apt-get update -y && sudo apt-get install -y build-essential && exit'); ...

Emitting and receiving socket io within the same file

node.js,express,socket.io

If you are trying to emit and listen for events within the same file, you should be using the built in event listeners for node, not the specialized ones for socket.io (https://nodejs.org/api/events.html): var EventEmitter = require('events').EventEmitter; var eventExample = new EventEmitter; //You can create event listeners: eventExample.on('anEvent', function(someData){ //Do something...