4

In my Ionic project, when I run a simple test code for require('fs'):

const fs = require('fs');
console.log(fs) //empty object {}
if(!fs.existsSync('./testFolder')){
    console.log('Folder not found');
}
else{
    console.log('Folder Found');
}

The error is

TypeError: fs.existsSync is not a function

But if I create a js file and run it on cmd like node test-fs, i can log out the fs object and get a result.

Any reason?


EDIT:

I hope to achieve this in the end:

var request = require('request');
var fs = require('fs');

var options = {
    url: 'https://some-url/api',
    headers: {
        "content-type": "application/json",
    },
    agentOptions: {
        pfx: fs.readFileSync(__dirname + '/certs/myCert.p12'),
        passphrase: ''
    }
};

request.get(options, (error, response, body) => {
    console.log(error);
    console.log(response);
    console.log(body);
});
Huiting
  • 1,368
  • 7
  • 24

1 Answers1

3

Filesystem module is a server side node module, it won't run inside the app, which is client side code. Instead for Ionic app use native file plugin

import { File } from '@ionic-native/file/ngx';

constructor(private file: File) { }
Amith Kumar
  • 4,400
  • 1
  • 21
  • 28
  • I have edited my question to show what I hope to achieve. Have seen alot of examples of using fs when making http requests involving certs. Will that not run also? – Huiting Jun 29 '19 at 04:22
  • 1
    @Huiting Those examples are probably node.js examples. Ionic is not node.js but a custom browser running your code – slebetman Jun 29 '19 at 05:22
  • 1
    NodeJs modules will not work inside ionic, Ionic is frontend, NodeJs is backend. For certificate based http call refer this [forum](https://forum.ionicframework.com/t/http-with-client-certificate-authentication/84791/7) for some guidance. – Amith Kumar Jun 29 '19 at 18:44