Ad

Node.js Require("fs") Gives Empty Object

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);
});
Ad

Answer

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) { }
Ad
source: stackoverflow.com
Ad