How to convert this code to use the Worker service

Hello everyone,
I would like to use the Worker service
currently my code looks like this, it handles calls from a javascript client, and the server reads and writes a json file locally.

is it possible to convert this code or use it with Worker? I have a doubt about reading and writing to a file, maybe Worker doesn’t allow it.

var port = process.env.PORT || 3000,
    express = require("express"),
    app = express();
var fs = require('fs');
var filename = 'shorturl.json';
var cors = require('cors');

app.use(cors({ origin: '*' }));
app.use(express.urlencoded());
app.use(express.json());

app.post('/writeJson', function(request, res) {
    fs.readFile(filename, 'utf-8', function(err, data) {
        data = JSON.parse(data);
        var obj = {
            id: request.body.user.id,
            concatURL: request.body.user.concatURL,
            chain: request.body.user.chain
        }

        data.storeDATA.push(obj)
        if (!err) {
            fs.writeFile(filename, JSON.stringify(data), (err) => {
                if (err) {
                    throw err;
                }
            });
        } else {
            throw err;
        }
    });
    res.send(200);
});

app.post('/readJson', function(request, response) {
    let rawdata = fs.readFileSync('shorturl.json');
    response.send(rawdata);
});

app.listen(port, function() {
    console.log("Running");
});
1 Like

Hi there - have you looked at Workers KV for this purpose? That will allow you to persist data that workers can read from and write to:

https://developers.cloudflare.com/workers/learning/how-kv-works

thanks, I’ll take a look

2 Likes

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.