Search code examples
angularionic3requirenwjs

Platform issue in require('os')


I have created an Ionic 3(A5) app. I am running this as node-webkit (NW.JS) app on Mac. If I write inside index.html script tag and check, require('os') platform returns 'darwin' and require('fs') returns full set of object correctly. But if I write same script inside a .ts file - require('os') platform returns 'browser' and require('fs') returns empty object.

I am using @types/node in devDependencies.

Code inside index.html -

 var os = require('os');
 var fs = require('fs');
 console.log('Log from index.html');
 console.log('platform = ' + os.platform());
 console.log('fs = ');
 console.log(fs);

Code inside app.component.ts -

var os = require('os');
var fs = require('fs');
console.log('Log from app.component.ts');
console.log('platform = ' + os.platform());
console.log('fs = ');
console.log(fs);

screenshot from nwjs console


Solution

  • Based on a reply from The Jared Wilcurt @TheJaredWilcurt on gitter.im,

    Node and Chromium don't know what a TS file is. you need to use something to transpile it to code that can actually be ran. TS is a meta-language, like Markdown, Sass, HAML, CoffeeScript, JSX, etc. Node only understands JavaScript, Chromium only understands HTML, CSS, and JS. If you are using something to transpile it and it alters your require statements, then that is the problem. You should inspect the actual code you are telling the environment to run.

    This was happening because the Ionic transpiler was changing the code in some way. I changed the code

    from

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

    to

    var os = nw.require('os');
    var fs = nw.require('fs');
    

    Now the only problem was that TypeScript compiler was not recognizing 'nw' as it was supposed to come at runtime. I have added

    declare var nw: any;
    

    on top. All fine now.