Saturday, 27 May 2017

node wildcard filename soundcloudjs

hi have daily recorded files to upload on soundcloud with cron on my directory record like Mike_27_05_2017_12_04_30.mp3

Tom_27_05_2017_10_00_00.mp3

how can i add the filename with wildcard automatically

the wildcard code not work asset_data: __dirname + '/record/Tom_*.mp3'

the code work asset_data: __dirname + '/record/Tom_27_05_2017_10_00_00.mp3'};



via Ambassador

npm module for clarifai not found when I start the node server

module.js:341
    throw err;
    ^

Error: Cannot find module 'clarifai'
    at Function.Module._resolveFilename (module.js:339:15)
    at Function.Module._load (module.js:290:25)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/Users/shiva/seefood-backend/app.js:4:16)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)

I get the above message in terminal when I do node app.js. I have installed Clarifai npm package as mentioned on https://developer.clarifai.com/quick-start/ with npm install clarifai but it still gives me this error. Do I need to install the package globally? Also this is my app.js :

var express = require('express')
var app = express();
var bodyParser = require('body-parser')
var Clarifai = require('clarifai')
var secrets = require('./secrets')
var keys = secrets.clarifaiConfig()

app.use(bodyParser.json());

var ClarifaiInstance = new Clarifai.App(
  keys.access_key,
  keys.secret_key
)

var store

var foodModel = 'bd367be194cf45149e75f01d59f77ba7'
var fnol = function getPredictionAsJSON(imageURL) {
  ClarifaiInstance.models.predict(foodModel, imageURL).then(
    function(response) {
      store = response.outputs[0].data
      console.log(store + ' from inside the fn');
    },
    function(err) {
      console.error(err);
    }
  );
  return store
}

app.listen(8000, function () {
  console.log('Recognize app listening on port 8000!')

  app.post('/classify', function(req, res) {
    var clarifaiData
    var imageURL = req.body.imageURL
      clarifaiData = fnol(imageURL)
      // console.log('cldata : '+ clarifaiData)
      var responseObject = {imageURL: imageURL, data: clarifaiData }
      // console.log('rObj : '+responseObject)
      res.send((responseObject));
  });

  app.get('/classify', function(req, res) {
    res.json((store));
  });
})



via ShivaV

How can I make use of weak references in javascript?

I have some very large objects that are used intensively, but occasionally in my Node.JS program. Loading these objects are expensive. In total they occupy more memory than I have in the system.

Is there any way to create a "weak reference" in Javascript, so that the garbage collector will remove my objects when memory is low, and then I can check whether the object is and reload it again if it was garbage collected since my last access?



via Bjorn Reppen

Query top level array of subdocs with MONGOOSE, to only return N most recent subdocuments in array

I'm looking for the conditions, fields, etc that i would need in a query, or an async flow to query a single document which has an array of subdocuments at the top-level.

Model:

let postSchema = new mongoose.Schema({
    date : {type: Boolean, require: true},
    message : {type: String, require: true}
});

let Post = new mongoose.Schema({
    locid: {type: String, unique: {indexed: true}, require: true},
    posts : {type: [postSchema], require: false}
});

Essentially, I would provide a Locid value as shown above into a function that i'm hoping would look like this:

Post.methods.getLastTwentyPostsForOne = function (locid) {
    return new Promise(function (values, error) {
        let p = new Post();
        p.find({"locid" : locid}, {/*...the conditions and elements here...*/}).exec()
            .then(function (found) {

                //..would return the last 20 posts, or less if there are less...

            }, function (err) {
                //..handle errors..
            })
    })
};

The most basic way i can think of doing this, would be to just fetch the whole array, and since mongo stores entries one after the other chronologically, to just parse the array and appending the last 20 or less posts contained in it into a final array (with a second promise-based function).

this makes the previous method, look like this:

function returnLastTwenty(posts) {
    return new Promise(function (results) {
        if (posts.length === 0) {
            return results([]);
        }
        if (posts.length <= 20) {
            return results(posts);
        }
        let length = posts.length;
        var next = [];
        for (i = length - 21; i < (length -1); i++) {
            next.append(posts[i]);
        }
        if (next.length === 20) {
            return results(next);
        } else {
            console.log('Some Error: found more than 20 posts, but parsed less');
            return results(next)
        }
    });
}

Post.methods.getLastTwentyPostsForOne = function (locid) {
    return new Promise(function (values, error) {
        let p = new Post();
        p.find({"locid" : locid})
            .then(function (found) {
                if (found.length === 1) {
                    returnLastTwenty(found[0].posts)
                        .then(function (results) {
                            return values(results)
                        })
                } else {
                    return error("Didn't find a unique document for locid: " + locid);
                }
            }, function (err) {
                return error(err)
            })
    })
};

While this does work.. the for loop and second async method seems too much.. Any clues as to how to achieve this with mongoose with a single query?



via murphguy

NodeJS read huge directory file by file

I have a directory composed of empty files and I want to iterate through each of their names. However I have nearly 20 million of these empty files and to load them all into memory with fs.readdir or fs.readdirSync would both take needlessly long and devour all my memory on the system.

What would be a way to go about this?

Ideally I would look for something that reads file by file in an async fashion with code that would ressemble the following:

readdirfilebyfile((filename)=>{....}) so that at no point would I keep the entire list of files in memory.

The current solution I am using is dumping all the file names into a single file which I then read as a data stream. However, this is just running away from a problem that I should know how to solve without resorting to this.



via Slava Knyazev

Webpage loads forever when file can't be found

I have a simple Express.js/Node.js website. If a file can't be found, the server is supposed to send a 404 error. But it doesn't work as expected. Let's say, if an image has the wrong URL, the webpage which the image is on will just keep on loading forever. How do I set up the error handlers properly so it stops loading if it detects a file doesn't exist?

This is my JavaScript:

var express = require('express'); // Express.js
var app = express();
var http = require('http');
var server = http.createServer(app);
var bodyParser = require('body-parser');
var postgres = require('pg'); // Postgres database

app.use(express.static('static', {
    extensions: ['html']
}));



app.all('*', function (request, response, next) {
    var redirectURL = request.query.redirect;
      if (redirectURL != undefined) {
        response.redirect(redirectURL);
      }
});

app.get('/', function (request, response, next) {
  response.redirect('/main/index');
});



// Handle 404 error
app.use(function(request, response) {
    response.status(400);
    response.send("Error 404!");
});

// Handle 500 error
app.use(function(error, request, response, next) {
    response.status(500);
    response.send("Error 500!");
});



server.listen(process.env.PORT || 8080, function () {
  console.log('Listening on port 8080!');
});



via repfarmer

return filename of uploaded file with multer and nodejs

I am creating a simple application as a learning experience with ionic 2 that connects to a node server running multer to upload images. The problem I am running into is, I need to get the final file name from multer back to the app that uploaded it, to save it locally. I am using the Auth and User modules from @ionic/cloud-angular for authentication and user information. The User object has a details object with things like "name", "email", "username", "image", ... So, when an image is uploaded to the node server and multer saves it, I need to get that filename back to the application so I can update the user.details.image property.

Here is a simple version of my node server...

var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var multer = require('multer');
var cors = require('cors');
var postStorage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './uploads');
    },
    filename: function(req, file, callback) {
        let fileName = '', postName;
        if(typeof req.body.postName !== "undefined") {
            postName = req.body.postName.toLowerCase().replace(/ /g, '-');
            filename += postName;
        }
        fileName += new Date().getTime();
        fileName += ".png";
        callback(null, fileName);
    }
});
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cors());
app.post('/upload', function(req, res) {
    var uploadPost = multer({storage: postStorage}).single('post_image');
    uploadPost(req, res, function(err) {
        if(err) {
            return res.end("error uploading file");
        }
        res.end("file uploaded");
    });
});
app.listen(app.get('port');
console.log("app listening on port: " _ app.get('port'));

Is there a way to have it send back the final file name that multer saved? Something like res.json({fileName: fileName}); res.end(); I really don't know at this point, and all the tutorials I can find on multer just show how to create a new filename and save a file in disk or database or memory, but nowhere does it show how you can actually get that filename back to the application that uploaded it. Thank you in advance for any help, I really appreciate it. If you need to see the ionic 2 code that uploads the stuff please let me know and I will update the post with that code as well. Thank you.



via Neglected Sanity