问题
This is a dead simple question and no doubt a duplicate but I've searched around and haven't found an answer which works. (Also I am a refugee from the world of Flex/Actionscript and am still getting used to the strange customs of this Javascript world 😉 )
I am testing the Jimp image lib and using a Jimp example (below). I created a new file,"jimpMethods.js", in a "js" directory and wrapped the Jimp example in a "testJimp" function. I wanted to reference the "house.jpg" in the "assets" directory of my project. I reference the "jimpMethods.js" in a script tag in my "index.html" and call "testJimp" in the "onLoad" event for the window.
My question: how do I reference the image file in my assets folder? The script itself is in the "JS" folder but it is executing within "index.html" which is in the enclosing directory.
I tried:
./assets/house.jpg // this would be relative to the "index.html"
../assets/house.jpg // this would be relative to the "JS" directory
Neither worked. I tried multiple variations and finally resorted to
__dirname + '/assets/house.jpg'
which did work (this is in Electron and __dirname
is a global var referencing the app folder).
I would like to understand what I was missing with my prior attempts: given my described directory structure, what is the correct relative path to my image?
My code in "JimpMethods.js
var Jimp = require("jimp");
function testJimp() {
var thePath = __dirname + '/assets/house.jpg'
Jimp.read(thePath, function (err, mmyImage) {
if (err) throw err;
mmyImage.resize(256, 256) // resize
.quality(60) // set JPEG quality
.greyscale() // set greyscale
.write(__dirname + '/assets/house-small-bw.jpg'); // save
});
}
The original Jimp example
var Jimp = require("jimp");
// open a file called "lenna.png"
Jimp.read("lenna.png", function (err, lenna) {
if (err) throw err;
lenna.resize(256, 256) // resize
.quality(60) // set JPEG quality
.greyscale() // set greyscale
.write("lena-small-bw.jpg"); // save
});
回答1:
Try to
console.log(__dirname)
you will see that it is not index.html you are starting with but main.js. You have to start with the path of the server or main script of your program. In your case it is main.js. So the following should work:
./app/assets/house.jpg
But using __dirname is a good solution and even better it would be using path.join.
来源:https://stackoverflow.com/questions/41775790/which-context-is-the-path-relative-to