Launching myapp as a service with the command "node myapp.js > myapp_error.log 2>&1" is identical in functionality

An easy-to-use testing application called myapp:

const fs = require("fs");
const json_encode = require('json_encode');

//simulating a real error
var wrong;
var test = json_encode(wrong);
//TypeError: Cannot read property 'replace' of undefined at json_encode... 

To save the error log for myapp as myapp_error.log from the command line, I use:

node myapp2.js > myapp_error.log 2>&1
//myapp_error.log is generated and the logged error can be viewed

Now, I need to achieve the same when starting myapp as a service in /etc/systemd/system, like so:

systemctl start myapp

The service (which has been tested and is running successfully) includes:

[Unit]
Description=myapp

[Service]
ExecStart=/path/to/myapp/myapp.js
Restart=my_username
User=nobody
Group=www-data
Environment=PATH=/usr/bin:/usr/local/bin
Environment=NODE_ENV=production
WorkingDirectory=/path/to/myapp

[Install]
WantedBy=multi-user.target

I have attempted:

ExecStart=/path/to/myapp/myapp.js > myapp_error.log 2>&1
(this doesn't work)

and also tried:

systemctl start myapp > myapp_error.log 2>&1
(this creates an empty file myapp_error.log in /etc/systemd/system)

Answer №1

Your unit file includes options for logging stdout/stderr in the [Service] block:

StandardOutput=append:/path/to/stdout.log
StandardError=append:/path/to/stderr.log

Note: (from comments discussion)

You also need to specify running node:

ExecStart=/usr/bin/node /path/to/myapp/myapp.js

Since systemd doesn't recognize JS files, you must call the correct interpreter before executing.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you identify duplicate entries using Mongoose?

I am currently working on a create function and encountering some code that closely resembles this: if(req.body.test !== undefined) { if(--req.body.test EXISTS IN test (model)--) { DO STUFF } else { ...

What is the best way to implement individual error handling for each function within combineLatest?

I'm looking for guidance on how to handle errors in each function within this `combineLatest` operation. Check out the code snippet below: const combined = combineLatest( this.myservice1.fn1(param), this.myservice2.fn2(), this.myservice3.fn3() ...

req.body is not defined or contains no data

I am facing an issue with my controllers and routers. bookController.js is functioning perfectly, but when I try to use userControllers for registration and login logic, req.body always appears empty. I tried logging the form data using console.log, but it ...

Generating requests using ExpressJS

Is it possible to send a POST request using a GET action? Although everything seems to be working fine, the "TOKEN" does not appear after the post. I am puzzled as to why this is happening. const request = require('request'); exports.g ...

An iteration in Javascript/NodeJS using the forEach loop

I am working with a forEach Loop in my code: <% users.forEach(function(user) { %> <tr> <td><%= user.studio %></td> <td><%= user.name %></td> <td><%= user.email %></td> ...

Building a node.js application with a mongoDB database from scratch

I am encountering an issue while attempting to print data collection using nodejs and mongo. The error that arises remains unresolved, what steps should be taken to correct this problem? For instance, consider the following schema: const bookSchema = new ...

Encountering an error of TypeError while attempting to generate a new GraphQL

Currently using Apollo-Server/TypeScript with graphql-tool's makeExecutableSchema() to set up schema/directives. Encountering an error while attempting to add a basic GraphQL Directive: TypeError: Class constructor SchemaDirectiveVisitor cannot be in ...

Verify the user's activity status in the MySQL database using Node.js by checking the timestamp of their last login

I have a query regarding user activity and deletion from the database. I need to determine when a user last logged in to see if their account is inactive. Unfortunately, I am unsure of how to tackle this task or check for the last login time. If anyone c ...

Configuring the Port for NodeJS Express App on Heroku

Currently, I am in the process of hosting my website on Heroku and configuring everything to ensure my app is up and running smoothly. However, each time I attempt to submit the form, undefined errors occur. For more details on the Undefined Errors and Co ...

Generate a set of random filtered results using mongoose in a Node.js environment

In my attempt to create a simple app for generating random exams, I have defined the following schemas: Question schema: var questionSchema = mongoose.Schema({ text: String, type: { type: String, enum: ['multichoice', 'numerica ...

Guide to setting the connection string for connect-pg-simple

The example provided on https://github.com/voxpelli/node-connect-pg-simple illustrates the following code snippet: var session = require('express-session'); app.use(session({ store: new (require('connect-pg-simple')(session))(), ...

Matching the cookie and header in express.js CSURF results in a 403 error code

My express server setup is quite simple: app.use(bodyParser.json()); app.use(cookieParser()); app.use(csurf({ cookie: true })); // routes app.use(Routes imported from another file); Currently, the client side consists of a basic form in react. ...

The Node.js Express error message displays an error in events.js at line 167 wherein an 'error' event is not being handled correctly

It seems like there is a syntax error in the bash_profile file on line 9. When trying to run the server using nodemon, an unexpected end of file error occurs. Nodemon is set to restart at any time and is currently watching for chan ...

Unresolved issue with Jade in Angular Routing

Currently, I am working on building a web server using expressjs and jade for the frontend. I have also implemented client-side routing with angularjs but unfortunately, my UI is not displaying as expected. Below you can find my code and the unexpected out ...

What are the potential security risks of placing NodeJS in the public HTML directory?

I have set up NodeJS for my server-side JavaScript, while using Apache to serve my web pages. Currently, my pages are loading Socket.IO locally by referencing node_modules/socket.io-client/dist/socket.io.js from the directory /var/www/html. The issue I a ...

Trouble with uploading images through multer is causing issues

When setting up multer, I followed this configuration let multer = require('multer'); let apiRoutes = express.Router(); let UPLOAD_PATH = '../uploads'; let storage = multer.diskStorage({ destination: (req, file, cb) => { ...

Is it possible to incorporate a setup phase in an express application?

Is it possible to create an array named res.locals.messages that stores messages generated in routes, like "phone number added to user"? Can a setup stage be established before any routes are executed to initialize this array? Are there more efficient meth ...

Error: The Node script encountered an issue and threw an EINVAL when attempting

I am currently using Ubuntu 12.10 and I have started working with Node.js. Initially, I installed node through the default Ubuntu repositories but encountered some issues. To resolve this, I decided to reinstall it from Chris Lea's repository which r ...

How to use Handlebars in Node.js to parse JSON data

When using Form API in node.js, I encountered JSON data that needs to be parsed. As a beginner, I am unsure how to handle this JSON data properly. [ { "Detail": " Rs. 1001 Full Talktime Topup Rs.1001 Full Talktime", "Amount": "1001", "Validity" ...

Finding it difficult to install the grpc-tools package using npm or yarn on a Mac M1 chip?

Steps for Installation: npm install -g grpc-tools yarn add global grpc-tools Encountered errors while attempting to install grpc-tools on Mac M1 Big Sur. The error messages are displayed below: npm ERR! code 1 npm ERR ...