Reputation: 7736
I have a plain text file named source.txt
I want to use a NodeJS script to do something to modify the content of the txt file and save as a new file, say output.txt
How do I do that?
I am expecting a command-line implementation, something like:
$node modify.js source.txt output.txt
Thanks!
Upvotes: 2
Views: 8656
Reputation: 18956
Sync style:
// save as: uppercase.js
var fs = require('fs');
var input = process.argv[2];
var output = process.argv[3];
var content = fs.readFileSync(input, 'utf8');
content = content.toUpperCase();
fs.writeFileSync(output, content);
Run:
$node uppercase source.txt output.txt
Upvotes: 4
Reputation: 72845
Use Node.js's build in fs()
function to read and write files to the local filesystem.
Basic read example:
fs.readFile('source.txt', function (err, data) {
if (err) throw err;
console.log(data);
});
Basic write example:
fs.writeFile('output.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});
Note: ensure your Node instance (and the account it's being run under) has appropriate permissions to the read and write source/destination.
Upvotes: 2