user3271960
user3271960

Reputation:

Node - multiple json files to API

I have a nodejs application that runs a cronjob task every so often and saves logs via ('node-persist') after every run. The log is a single object in a .json file. If I want to set up an API w/ Express so users can fetch the last 'X' .json logs from that persist folder, what would be the best way to achieve that? Is there another library to make this process easy? I'm a front-end guy, trying to hack my way around node, so thanks for your help in advance everyone!

Ideally, I want the user to request /get/logs and I return an array of objects that live on the individual persist .json file created after the associated run.

Upvotes: 1

Views: 399

Answers (1)

Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

You can do it. This is the code. Don't forget to install express. npm i express.

The user can get the X last logs, by using call to '/get/logs?limit=X'.

var express = require('express')
var storage = require('node-persist');
storage.initSync();
var app = express()    
app.get('/get/logs', function(req, res) {

    var limit = req.query.limit; // get the limit from the query string (/get/logs?limit=X'
    var values = storage.values(); // get all values
    values = values.slice(0, -1 * limit) // get last X values
    res.send(values)
})

require('http').createServer(app).listen(80)  // Create an http server that listen to port 80

Upvotes: 0

Related Questions