Search code examples
node.jselectronabsolute-path

if __dirname gets you the folders your in what gets you the root of the project?


Consider the following project structure:

enter image description here

in game.js I have the following:

import React, {Component} from 'react';
import {Loop, Canvas, Sprite}     from '../components/';
import GameLoop           from '../engine/loop';
import path               from 'path';

export default class Game extends Component {

  constructor(props) {
    super(props);
  }

  render() {
    console.log();
    return (
      <Loop>
        <Canvas>
          <Sprite img={'/images/The-Poet.png'} />
        </Canvas>
      </Loop>
    );
  }
}

If you look at Sprite I am trying to pass in an image, how ever in electron I get the error:

Failed to load resource: net::ERR_FILE_NOT_FOUND file:///images/The-Poet.png

If I try and use __dirname it spits out src/game/... I need the absolute path to said image. Ideas?


Solution

  • You can build the absolute path by getting the path to the current application directory using app.getAppPath()

    http://electron.atom.io/docs/api/app/#appgetapppath

    Since app is a main process variable and you are wanting this in the renderer process, you will have to require it using remote.

    var remote = require('remote')
    var app = remote.require('app')