I want to make a simple node module that can be run from the command line that I can input files into, then it might change every instance of 'red' to 'blue' for example and then save that as a new file. Is there a simple example out there somewhere that I can edit to fit my purposes? I've tried looking but couldn't find one that was sufficiently simple to understand how to modify it. Can anyone help?
A simple example of replace.js (both old and new files are supposed to be in UTF-8 encoding):
'use strict';
const fs = require('fs');
const oldFilePath = process.argv[2];
const newFilePath = process.argv[3];
const oldFileContent = fs.readFileSync(oldFilePath, 'utf8');
const newFileContent = oldFileContent.replace(/red/g, 'blue');
fs.writeFileSync(newFilePath, newFileContent);
How to call:
node replace.js test.txt new_test.txt
Documentation on used API:
process.argv
fs.readFileSync()
fs.writeFileSync()
Related
I need to read a text file line by line in JavaScript.
I might want to do something with each line (e.g. skip or modify it) and write the line to another file. But the specific actions are out of the scope of this question.
There are many questions with similar wording, but most actually read the whole file into memory in one step instead of reading line by line. So those solutions are unusable for bigger files.
With Node.js a new function was added in v18.11.0 to read files line by line
filehandle.readLines([options])
This is how you use this with a text file you want to read
import { open } from 'node:fs/promises';
myFileReader();
async function myFileReader() {
const file = await open('./TextFileName.txt');
for await (const line of file.readLines()) {
console.log(line)
}
}
To understand more read Node.js documentation here is the link for file system readlines():
https://nodejs.org/api/fs.html#filehandlereadlinesoptions
The code to read a text file line by line is indeed surprisingly non-trivial and hard to discover.
This code uses NodeJS' readline module to read and write text file line by line. It can work on big files.
const fs = require("fs");
const readline = require("readline");
const input_path = "input.txt";
const output_path = "output.txt";
const inputStream = fs.createReadStream(input_path);
const outputStream = fs.createWriteStream(output_path, { encoding: "utf8" });
var lineReader = readline.createInterface({
input: inputStream,
terminal: false,
});
lineReader.on("line", function (line) {
outputStream.write(line + "\n");
});
I'm coding a bot with Discord.js, and was wondering how to create a function for a play command.
!play
faded
I want the code to search through a set folder, located at ./MusicFiles and find the filename closest to the given argument after the command !play. How would I do this and how would I give the full name of the file so it can be used by the bot?
You can use the npm packages levenary and fs. levenary is a package that will calculate the Levenshtein Distance between two strings. For example:
levenary('cat', ['cow', 'dog', 'pig']);
//=> 'cow'
You can use this in combination with fs, a package with can return an array of all files within a directory.
const fs = require('fs');
const levenary = require('levenary')
const files = fs.readdirSync('./MusicFiles') // get every file in this directory
const songFile = levenary(args[0], files) // get the file
I want a logger for my project. Everytime I call myConsole.log it overwrites the existing log. what can i do that the it just write it in the next line and not delete everything
const fs = require('fs');
const myConsole = new console.Console(fs.createWriteStream('./output.log'));
myConsole.log(var)
myConsole.log(var2)
myConsole.log(var3)
I'd reccomend looking at Winston, which is a package that does great logging.
But with your code, you need to add the a (append) flag to your fs writer so it writes properly rather than overwriting (default flag is w), like so:
const myConsole = new console.Console(fs.createWriteStream('./output.log', { flags: 'a' }));
See docs on createwritestream and system flags.
You can pass { flags: 'a'} as options argument to the createWriteStream call.
This flag will open the file for appending instead of overwriting
I have the following script:
const lib = require('./lib.js');
const fs = require('fs');
const graph = fs.readFileSync('../js-working-dir/add_graph.pb', 'utf8');
const sess = new lib.Session(graph);
const results = sess.run({"a": 5, "b": 6}, ["o"]);
console.log(results[0]);
(For context lib.js is a compiled emscripten module; it is fairly big, approximately 40MB, otherwise I would upload it.)
When I execute this script in node, it works fine. However when I execute it in the REPL (same working directory and everything) my code hangs on const sess = new lib.Session(graph);.
Any ideas of why this might be the case? Does Emscripten treat the REPL and node execution differently? Is there a way I can debug where it is getting stuck?
Thanks so much,
Problem found, appears to be a bug in urandom...
https://github.com/kripken/emscripten/issues/4905
I am trying to write data to a text file in Node.js. When initializing the write stream I get the following error message:
Be sure you have included at the top of your node program
var fs = require('fs');
Also It looks like you spelled 'Stream' incorrectly
fs.createWriteSteam > fs.createWriteStream
Another issue that may come up is trying to get createWriteStream from 'fs/promises'.
It doesn't exist on 'fs/promises'. (At least on NodeJS version 14);
My solution was to import both:
var fs = require('fs');
var fsPromises = require('fs/promises');