Skip to content Skip to sidebar Skip to footer

How To Translate This Python Code To Node.js

I got a very nice answer on here about how to clear a line / delete a line in a file without having to truncate the file or replace the file with a new version of the file, here's

Solution 1:

You should take into consideration the newline character at the end of each line, that is not included in the 'line' you're getting via the readline module. That is, you should update position to position += (line.length + 1), and then when writing, just use position (without the -1).

Solution 2:

Ok, I think I got it, but if someone has any beef with this please feel free to critique. It's close, but it needs some fine tuning I think, there seems to be an off-by-one error or something like that.

#!/usr/bin/env nodeconst readline = require('readline');
const fs = require('fs');

const file = process.argv[2];
const rgx = newRegExp(process.argv[3]);

const fd = fs.openSync(file, 'r+');

const rl = readline.createInterface({
    input: fs.createReadStream(null, {fd: fd})
});

let position = 0;

constonLine = line => {

    if (String(line).match(rgx)) {

        let len = line.length;

        rl.close();
        rl.removeListener('line', onLine);

        // output the line that will be replaced/removed
        process.stdout.write(line + '\n');

        fs.write(fd, newArray(len + 1).join(' '), position, 'utf8',

            (err, written, string) => {

            if (err) {
                process.stderr.write(err.stack || err);
                return process.exit(1);
            }
            else {
                process.exit(0);
            }

        });

    }

   position += (line.length + 1);  // 1 is length of \n character

};

rl.on('line', onLine);

Post a Comment for "How To Translate This Python Code To Node.js"