Nick Nick - 3 months ago 9
Linux Question

readFileSync throws error when server launched as linux service

i'm trying to make a simple api for myself using a node/express server running on digital ocean. in the server file i have something like this:

var data = fs.readFileSync('path/to/data.json','utf8');


which works perfectly fine when i launch the server manually from the cmd line

node server


but what i have setup is a linux service so that everytime i restart my digital ocean machine it will automatically launch the server, the service ( kept in etc/init/ ) looks like this:

start on filesystem and started networking
respawn
exec node /path/to/server.js


the issue is that when I make the request to the server that runs the readFileSync call it works fine if the server had been launched manually from the cmd line, but when the server was launched via the service then the readFileSync throws the following error:

Error: ENOENT, no such file or directory 'path/to/data.json'
at Error (native)
at Object.fs.openSync (fs.js:500:18)
at Object.fs.readFileSync (fs.js:352:15)


the file and the directory do exist ( if i make a request for the data.json file directly in my browser i can see it )

what am i missing? is there something about launching the server as a service that conflics with using readFileSync? is there an alternative approach to what i'm trying to do? should i use some kind of request/fetch resource module for accessing that json file?

Answer

You're using a relative path but the process is not being started from where you think it is. Instead of using relative paths, use absolute paths.

So if your layout looks like:

server.js
path/
  to/
    data.json

Then inside your server.js, you can just do something like:

var path = require('path');

// ...

var data = fs.readFileSync(path.join(__dirname, 'path/to/data.json'), 'utf8');