user10457278
user10457278

Reputation:

How do I read an input file, modify its contents and save the result to an output file with node.js?

In my project I have an input file like in this program :

 var fs = require('fs');
 var str = fs.readFileSync('input.txt', 'utf8');

But I had to use this command in my terminal :

cat input.txt | ./prog.sh > result.txt

Can you help me please, because I didn't find how can I code a general input file in JS with this kind of command in the terminal ?

Upvotes: 2

Views: 115

Answers (2)

user10457278
user10457278

Reputation:

The following code permit to take every name type of document at the entry of the terminal command, this code works well :

#!/usr/bin/env node

let chunk = "";

process.stdin.on("data", data => {
    chunk += data.toString();
});

process.stdin.on("end", () => {
    chunk.replace(/^\s*[\r\n]/gm,"").split(/\s+/).forEach(function (s) {
        process.stdout.write(
        s === 'bob'
        ? 'boy \n'
        : s === 'alicia'
           ? 'girl\n'
           : s === 'cookie'
               ? 'dog \n'
               : 'unknown \n');
    });
});

We can execute it correctly with the following command : cat input.txt | /prog2.js > result.txt

Upvotes: 1

holaymolay
holaymolay

Reputation: 580

This should completely overwrite the result.txt file or create it anew if it doesn't exist.

const fs = require('fs');

const inputFile = "./input.txt"; 
const outputFile = "./result.txt";

var str = fs.readFileSync('input.txt', 'utf8').toString();

var prog = (fileStr) => {
  let modifiedStr = fileStr.trim() + " !!!modified!!!"; // do something to modify the string
  return modifiedStr;
};

let fileContents = prog(str);

fs.writeFile(outputFile, fileContents, function(err){
  if (err) throw err;
  console.log('string saved to ' + outputFile);
});

Upvotes: 0

Related Questions