Execute a shell command from react native app for mac os

Viewed 777

I am trying to build a mac os application based on react native(https://github.com/ptmt/react-native-macos) that execute a shell script and show output on the app. I wanted to start by running a simple ls command.

Documentation - https://nodejs.org/api/child_process.html#child_process_spawning_bat_and_cmd_files_on_windows

Following is my code

import React from 'react';
import {
  Button,
  SafeAreaView,
  ScrollView,
  StatusBar,
  StyleSheet,
  Text,
  View,
} from 'react-native';
import {Colors} from 'react-native/Libraries/NewAppScreen';
const {spawn} = require('child_process');

class App extends React.Component {
  super;
  constructor(props) {
    super(props);
    this.state = {
      textValue: 'Change me',
    };
  }

  onPress = () => {
    const ls = spawn('ls', ['-lh', '/usr']);
    ls.stdout.on('data', data => {
      console.log(`stdout: ${data}`);
      this.setState({
        textValue: data,
      });
    });
  };

  render() {
    return (
      <>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            style={styles.scrollView}>
            <View style={{paddingTop: 25}}>
              <Text>{this.state.textValue}</Text>
              <Button title="Change Text" onPress={this.onPress} />
            </View>
          </ScrollView>
        </SafeAreaView>
      </>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  body: {
    backgroundColor: Colors.white,
  },
});

export default App;

But is throwing below error.

error: Error: Unable to resolve module child_process from /Users/Ramu/apps/PdfTools/App.js: child_process could not be found within the project.

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
  10 | } from 'react-native';
  11 | import {Colors} from 'react-native/Libraries/NewAppScreen';
> 12 | const {spawn} = require('child_process');
     |                          ^

I hope child_process should be part of react native bundle. Could some body please help on how to fix it.

1 Answers
Related