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

Getting the Correct Information from Upload Files in jQuery and PHP

While experimenting with the jquery plugin called jquery.filer, I encountered an issue during file upload on their official website . The returned value I received looked like this: { "files": [ "..\/uploads\/dK079QrL2g.docx" ], "metas": [ ...

tips for personalizing your jQuery image preview script

Currently, I have implemented a jQuery script that allows me to preview multiple images before uploading them. Although the functionality works well, I am facing difficulties customizing it to meet my specific requirements. <script> $(document).r ...

Modifying the appearance of a CSS element with jQuery: Step-by-step guide

The code I have is as follows: $('.signup-form-wrapper').css("style", "display: block"); $('.login-form-wrapper').css("style", "display: none"); I'm not sure why it's not working. The current appearance of ...

Difficulty altering value in dropdown using onChange function - Material-UI Select in React app

Having trouble updating dropdown values with MUI's Select component. The value doesn't change when I use the onChange handler, it always stays the same even after selecting a new item from the dropdown. I made a functional example on CodeSanbox. ...

Find the elements of <a> tags specifically without the attribute href

Currently, I am extracting the class of all <a> elements in an HTML document of a webpage using VB.net from a WinForm: Dim htmlLinks As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("a") For Each link As HtmlElement In htmlLi ...

What is the best method for extracting the innerHTML value of html tags using a css selector or xpath?

I am currently struggling with retrieving the HTML inner text value using CSS selector or XPath. While I can achieve this using document.getElementById, I am unable to do so using selectors. I can only print the tag element but not the text from it. For e ...

What is the best way to upload images in Vue.js without using base64 formatting?

Is there a way to upload an image file without it being base64 encoded? I currently can only achieve base64 format when trying to upload an image. How can I modify the code to allow for regular file uploads? <script> submitBox = new Vue({ el: "#su ...

Refresh the React state at regular intervals

constructor(){ super(); this.state={ numbers : [1,2,3,4,1,2,3,4,1,3,1,4,12,2,3,2] }; } componentDidMount(){setInterval(this.updateNumbers(),5000);} updateNumbers() { console.log(this.props.newData); let numbers = this.state.nu ...

Updating the DOM after scrolling using jQuery

jQuery hover functionality is not working correctly after scrolling. $(document).ready(function() { $('img').hover(function(){ alert('hello'); },function(){ alert('hello not'); }); }); When hoveri ...

Refining/searching with selectors in AJAX response

As someone who is new to javascript and coding in general, I am facing a challenge with filtering and manipulating data received through an AJAX request. Unfortunately, I do not have access to the server-side code. The server responds with rota information ...

Differences in outcomes have been observed between the elementLocated and findElements functions

Currently, I am in the process of developing Webdriver automation for a specific web application. As part of this process, I have created a test that seems to be functioning well most of the time but occasionally encounters an issue. it('verifies pre ...

Discover the steps for generating this graph using ZingChart

I have been experimenting with ZingChart in an attempt to replicate a chart that has the same look and functionality as this example: https://i.stack.imgur.com/PGNK3.png Despite making numerous adjustments to a bar chart, I have not been able to achieve ...

How can I manually set a date in Angular bootstrap datepicker?

Using the Angularjs Bootstrap datepicker has been a great experience, but I encountered a problem when attempting to select the date using JavaScript. How can I ensure that the selected date in the datepicker matches the date read from a specific object, s ...

The function $.post(...) is failing to detect the JSON content in the

I am attempting to send a POST request to the server using the following code: var body = { PatientAgeFilter: { CompareOperator: parseInt(self.patientAge()), MoreThanVal: { AgeSpecifier: 0, AgeValue: parseInt(se ...

The function window.open has been disabled on codepen.io site

My dilemma involves a button designed to open a random Wikipedia page. While the code works perfectly in the CodePen editor, I encounter issues when opening it in full-page view. The problem arises when the log displays 'window.open is disabled'. ...

Utilizing Google Maps API to update ImageMapType Overlay

I am utilizing the Google Maps JavaScript API to showcase weather data from a tile server. The specific tile server can be accessed here: To display the tile server, I am utilizing an ImageMapType and incorporating it into the Google Map's overlayMap ...

Retrieving JavaScript return values in a C# WebBrowser control within a WPF application

I utilized JavaScript injection into WebBrowser control in C# (System.Windows.Controls.WebBrowser) to achieve, <C#> IHTMLDocument2 webdoc = (IHTMLDocument2)webBrowser1.Document; string var = File.ReadAllText("C:/.../Resources/script.txt"); object re ...

Trouble with value updating in PostgreSQL with NodeJs

var express = require('express'); var app = express(); var pg = require('pg'); var connectionString = "postgresql://postgres:sujay123@localhost:3001/redc"; app.use(express.static('public')); app.get('/index.h ...

Looking to add tiered custom attribute select boxes in SnipCart - how can I make it happen?

I am interested in implementing two custom attributes for products, where the options for the second custom attribute are determined by the selection of the first attribute. My specific situation involves selling art in various formats and sizes, with dif ...

Automatically update div content using AJAX in a different approach

In my situation, I am facing a unique challenge compared to other queries. I have a div element with the following code <div id="ondiv"><?php ?></div> Within this PHP section are details of people who are currently online. Ideally, when ...