Is it possible for JavaScript code to access a file input from the terminal?

When I run the command

cat input.txt | node prog.js >result.txt
in my terminal, I need to use an input file.

This is my code:

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

str.replace(/^\s*[\r\n]/gm,"").split(/\s+/).forEach(function (s) {
    return console.log(
    s === 'bob'
        ? 'boy'
        : s === 'alicia'
        ? 'girl'
        : s === 'cookie'
        ? 'dog'
        : 'unknown');
});

I would like my code to be able to handle any input document name entered by the user. How can I achieve this functionality?

Answer №1

If you send a value to a node.js script through piping, you must listen for the readable or data event listeners available to the process object. Using the data event listener puts the stream into flowing mode automatically, but if you use the readable event listener, you need to manually switch stdin to flowing mode by using process.stdin.read(). When writing to another command or script, use process.stdout.write(), as it's a writable stream.

Flowing mode

#!/usr/bin/env node

let chunks = "";

process.stdin.on("data", data => {
    // Convert Buffer instance data to string
    chunks += data.toString();
})

// Triggered when there is no more data to read
process.stdin.on("end", () => {
    // Pipe out the data or write to a file
    process.stdout.write(chunks);
});

Non Flowing mode

#!/usr/bin/env node

process.stdin.on("readable", () => {
    const flowingMode = process.stdin.read();
    // Will be null if there is no more data to read
    if (flowingMode)
        chunks += flowingMode.toString();
})

process.stdin.on("end", () => {
    process.stdout.write(chunks);   
})

To simplify handling of readable and data events:

#!/usr/bin/env node

process.stdin.pipe(process.stdout);

To execute logic on the end event listener trigger:

#!/usr/bin/env node

process.stdin.pipe(process.stdout, { end: false });

process.stdin.on("end", () => /* your logic here */);

Example usage when handling the end event:

#!/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'
                : s === 'alicia'
                    ? 'girl'
                    : s === 'cookie'
                        ? 'dog'
                        : 'unknown');
    });
});

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

Answer №2

To pipe something into a Node script, you must utilize the process.stdin as highlighted by @T.J.Crowder.

For further insight on this topic, refer to the following article which provides a detailed explanation along with a practical example: e.g.:

#!/usr/bin/env node 
const readInput = callback => {
  let input = '';
  process.stdin.setEncoding('utf8');
  process.stdin.on('readable', () => {
      const chunk = process.stdin.read();
      if (chunk !== null) {
          input += chunk;
      }
  });
  process.stdin.on('end', () => callback(input));
}
readInput(console.log);

Answer №3

Are you wondering how to retrieve data from the standard input? The solution is to utilize process.stdin, which functions as a Stream.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing delays when loading more than 200 input fields on the screen due to

So I've been working on a project that involves having potentially unlimited input fields. However, once I add around 200 items, the performance starts to degrade significantly. You can see a demo of this issue here: (To test: Focus on the last input ...

Tap and hold with Zepto

I've been on the hunt for a Zepto plugin that can handle a longClick event. While Zepto already supports longTap, which is perfect for mobile devices, I need something specifically for desktop browsers when a user clicks and holds. It's also impo ...

How can I capture a screenshot of the div displaying pictures uploaded by the user on the frontend?

Take a look at this code snippet. It allows users to upload images, move them around, resize, and rotate them once uploaded. $(function() { var inputLocalFont = $("#user_file"); inputLocalFont.change(previewImages); function previewImages() { ...

What is causing the rejection to stay suppressed?

I noticed that when function uploadLogs() is rejected, the expected rejection bubbling up to be handled by function reject(reason) does not occur. Why is this happening? In the code below, a rejection handler for function uploadLogs() successfully handles ...

Tips for passing an object as an argument to a function with optional object properties in TypeScript

Consider a scenario where I have a function in my TypeScript API that interacts with a database. export const getClientByEmailOrId = async (data: { email: any, id: any }) => { return knex(tableName) .first() .modify((x: any) => { if ( ...

Exploring the Possibilities of WebAudio API through Asynchronous Events

Is there a way to trigger events after an oscillator finishes playing using the webaudio API? I am attempting to update my Vue component reactively to display data in the DOM while a note is being played. Here's a snippet of my code: <template> ...

What is the best way to link this to a function in AngularIO's Observable::subscribe method?

Many examples use the Observable.subscribe() function in AngularIO. However, I have only seen anonymous functions being used like this: bar().subscribe(data => this.data = data, ...); When I try to use a function from the same class like this: update ...

Exploring the depths of AngularJS through manual injection

I seem to have misunderstood the tutorial and am struggling to get manual injection working on my project. As I'm preparing to minify and mangle my JS code, I decided to manually inject all my modules and controllers. However, I keep encountering err ...

It appears as though the promise will never come to fruition

I am currently developing an application that is designed to search for subdomains related to a specific domain and store them in a database. The application retrieves data from crt.sh and threatcrowd. One of the functions within the application parses th ...

Having trouble aligning material-ui GridList in the center

I am currently working with a GridList in order to display Cards. The styling for these components is set up as shown below: card.js const useStyles = makeStyles({ card: { maxWidth: 240, margin: 10 }, media: { heigh ...

Exploring the Differences Between Next.js Script Components and Regular Script Tags with async and defer Attributes

Can you explain the distinctions between the next js <Script /> component rendering strategies such as afterInteracive, beforeInteractive, and lazyLoad, as opposed to utilizing a standard <script /> tag with attributes like async and defer? ...

Choose all the checkboxes that use Knockout JS

Struggling with implementing a "select all" checkbox feature as a Junior developer on a complex project utilizing knockout.Js and Typescript. I can't seem to figure out how to select all existing checkboxes. Here is the HTML: <td> <inp ...

Combining arrays of objects in JavaScript

I am currently working on combining different arrays: const info1 = {id: 1} const info2 = {id: 2} const info3 = {id: 3} const array1 = [info1, info2] const array2 = [info1, info3] const array3 = [info2, info3] const union = [...new Set([...array1, ...arr ...

I encountered an issue while operating my next.js application which utilizes solidity smart contracts. The error message "Cannot read properties of undefined" was displayed during the process

While working on my next.js app and attempting to fetch user data, I encountered the "cannot read properties of undefined" error. https://i.stack.imgur.com/SBPBf.png I also received the following error in the console https://i.stack.imgur.com/JBtbO.png ...

Initially, the OWL Carousel image is not displaying correctly due to incorrect sizing

I am currently working with OWL Carousel and have implemented a code that displays one image at a time, with the next image sliding in every 15 seconds. The width is set to occupy 100% of the screen and I have configured the JavaScript accordingly so that ...

Is there a method similar to insertBefore that works with arrays and/or HTMLCollections?

Is there a vanilla JavaScript or jQuery function that works like Node.insertBefore(), but for arrays and/or HTMLCollections? An example of what I'm looking for: var list = document.getElementsByClassName("stuff"); var nodeToMove = list[0]; var other ...

After AngularJS has loaded, CSS animations seem to be ineffective

When loading a page, I have created a div that is displayed. Here is the code: <div ng-show="load" class="rb-animate-time rb-animate-hide rb-load"> <div class="text">Hello world</div> </div> <div ng-init="load = false">&l ...

What could be causing XMLHttpRequest to encounter issues with the readystate and status states while running on localhost

Hey guys, I'm having some trouble with this code and can't figure out why it's not working. Here is the code snippet: <script> function findMatch() { if(window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

Transmit an Array using Ajax and retrieve it on an ASP Classic page

I am facing a challenge where I need to pass an array using AJAX on an ASP page. After trying to send it as GET method and checking the data being received, I noticed that only the LAST record of the array is being processed by ASP. How can I successfu ...