I have a server.js file defined as follows:
var iniparser = require('iniparser');
var inihost;
var inidbuser;
var inidbpass;
var inidbname;
var config = iniparser.parseSync('../setup_db/config.ini');
inihost = config.db_hostname;
inidbuser=config.db_username;
inidbpass=config.db_password;
inidbname=config.db_name;
.....
on reboot I have a crontab that should automatically forever starts the server:
#reboot /usr/bin/sudo /usr/local/bin/forever start /var/www/html/rubrica/chat/server.js
Interestingly if I launch the server from any directory with the complete path like:
forever start /var/www/html/rubrica/chat/server.js
the server starts just fine..if , however, i run the SAME command from withtin the /root/.forever/ directory the server will give me the following error:
ENOENT, no such file or directory '../setup_db/config.ini'
So whenever i reboot the machine I get that error...how is such a thing possible?
The argument to iniparser.parseSync() is not relative to the current file like require() but rather the current working directory. Use:
var path = require('path');
var config = iniparser.parseSync(path.join(__dirname, '../setup_db/config.ini'));
Related
I am attempting to run a file in my node environment on my macbook. I keep getting the following terminal error messages:
/.../filename.js: line 2: syntax error near unexpected token `('
/.../filename.js: line 2: `const fs = require('../build/index.js');'
code:
#!/usr/bin/env node
const fs = require('../build/index.js');
The command I'm giving is:
node index.js
(I know the file names are the same but its calling a different file.)
I can't seem to figure out why it is finding the extra `.
I have tried:
Rewriting the code multiple times.
I started a new file from scratch with the same name (filename.js).
Running the code through jslint
https://www.digitalocean.com/community/questions/syntax-error-near-unexpected-token-in-node-js-for-http
I followed the exact formatting from this article: https://adrianmejia.com/blog/2016/08/12/getting-started-with-node-js-modules-require-exports-imports-npm-and-beyond/
Using double quotes instead of single quotes
Little more background, this is a project I've picked up and this is my first time trying to run it.
EDIT: Code for index.js
'use strict';
var _child_process = require('child_process');
var _logger = require('./logger');
var _logger2 = _interopRequireDefault(_logger);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var l = new _logger2.default();
l.log('Starting backup');
var wd = __dirname.split('/');
var basePath = wd.slice(0, wd.length - 1).join('/');
var execPath = basePath + '/path/filename.js';
var stdout = (0, _child_process.execSync)('. ' + execPath + ' -a ' + basePath + '/something.json -b ' + basePath + '/backups');
l.log(stdout);
The issue is that the index.js calls filename.js through child_process.execSync() method, that's basically "execute this file using shell and give me its output".
Your filename.js has a shebang, and it would do intended (run using node), if not for this tiny dot in execSync() first parameter. It looks like this:
. /some/path/filename.js -a /some/path/something.json -b /some/path/backups
In sh-shells the . is a shorthand for source builtin command, that means "execute this file in shell and return its exit code". Thus, filename.js executes in shell, not in the node.
Just remove this dot (with space after it) and it will work.
I am trying to repeatedly update a file using a cronjob. Eventually, this is going to be more complicated but for now I'm trying to figure out my current problem. I know the code below is somewhat over-complicated because I preserved the basic structure while trying to problem solve. Here is the server file:
// server.js
var express = require('express');
var port = process.env.PORT || 8080;
var http = require('http');
var fs = require("fs");
var curtainup = require('./diagnoseleak.js');
var url = require("url" );
var app = express();
// launch ======================================================================
app.listen(port);
//run the CronJob
var CronJob = require('cron').CronJob;
new CronJob('0 * * * * *', function() {
console.log("running");
var date = new Date();
console.log("Ran at: "+date.getHours()+":"+date.getMinutes());
curtainup.doitnow();
} , null, true, 'America/New_York');
And here is the file referenced called diagnoseleak.js:
var fs = require("fs");
var mostRecentLocation = "./config/pullfiles/mostRecent55.txt";
module.exports = {
doitnow: function(){
var writethefile = function(){
fs.writeFileSync(mostRecentLocation, "A file called mostRecent55 should be create with this text", { flag: 'w' });
console.log("This should write to the console");
}
writethefile();
}
}
From the directory that houses the server file, I type the following into cmd:
git add .
git commit -m "adding files"
git push heroku master
heroku run bash
Then into the bash window I type:
cd config/pullfiles
ls -l
AND...no file called mostRecent55.txt appears. Am I looking in the wrong place? Eventually I want to be able to update a file, but I have a feeling I'm either looking in the wrong place for this mostRecet55.txt file or going about the process of writing it incorrectly.
heroku doesn't let you write files onto the filesystem where your app is stored. You would need to use an add-on, database or external service of some kind. The only exception seems to be /tmp which is only temporary storage
If I run my node.js script in the containing directory, it runs fine. If I run it from crontab with
*/1 * * * * /usr/local/bin/node /Users/full/path/to/main >> ~/mtf.log
I see errors relating to the twilio config
var TWClient = require('twilio')(configTwilio.accountSid, configTwilio.
^
TypeError: Cannot read property 'accountSid' of undefined
Why doesn't this work when run from cron? The same behaviour occurs on the server (ubuntu) and localhost (OSX 10.8.5)
Top of script (main.js)
var phantom = require('phantom');
var portscanner = require('portscanner');
var FeedParser = require('feedparser'),
request = require('request');
var configDB = require('config').DB;
var configTwilio = require('config').Twilio;
var mysql = require('mysql');
var TWClient = require('twilio')(configTwilio.accountSid, configTwilio.authToken);
The config file default.yaml is in the config directory relative to main.js and contains (redacted):
DB:
dbHost: localhost
dbPort: 3306
dbName: xxx
dbUser: xxx
dbPass: xxx
Twilio:
accountSid: AC8fxxxxxxxxd5f7aace47a8
authToken: d863b4ddfxxxxxx9b7c845
I've also tried this locally:
env -i sh -c 'cd /path/to/script && /usr/local/bin/node main'
but get:
events.js:72
throw er; // Unhandled 'error' event
^
Error: spawn ENOENT
If you try wrapping it inside a shell script, you may have success with setting some environment variables in the crontab entry.
See this answer to a similar question:
https://stackoverflow.com/a/27823675/608269
When you schedule a cron task, the node js won't identify the config json files in your local directory. Add the code below in your main.js file to change the node config directory.
process.env.NODE_CONFIG_DIR= __dirname +'/config';
var config = require('config');
I want the equivalent of $PROGRAM_NAME in Ruby, or ARGV[0] in C-likes, for Node.js. When I have a Node script that looks something like this,
#!/usr/bin/env node
console.log(process.argv[0])
… I get “node” instead of the name of the file that code is saved in. How do I get around this?
You can either use this (if called from your main.js file):
var path = require('path');
var programName = path.basename(__filename);
Or this, anywhere:
var path = require('path');
var programName = path.basename(process.argv[1]);
Use __filename? It returns the currently executing script.
http://nodejs.org/docs/latest/api/globals.html#globals_filename
For working with command line option strings check out the optimist module by Substack. Optimist will make your life much easier.
var inspect = require('eyespect').inspector();
var optimist = require('optimist')
var path = require('path');
var argv = optimist.argv
inspect(argv, 'argv')
var programName = path.basename(__filename);
inspect(programName, 'programName')
To install the needed dependencies:
npm install -S eyespect optimist
I am using readDirSync to get the files from a Diretory. PLease find the code and error as following.
var fs = require('fs');
var files = fs.readdirSync('./application/models/');
for(var i in files) {
var definition = require('../application/models/'+files[i]).Model;
console.log('Model Loaded: ' + files[i]);
}
I am getting error for line number 2 .
ENOENT, No such file or directory './application/models/' at Object.readdirSync (fs.js:376:18)
I have application/models on the same dir. I already checked for '/application/models/' and
'application/models/' but failed. I can see the same thing running on server.
Please help
Thanks
If you are using relative path when calling readdirSync, make sure it is relative to process.cwd().
However, "require" should be relative to the current script.
For example, given the following structure
server.js (node process)
/lib/importer.js (the current script)
/lib/application/models/
you may need to write importer.js as:
var fs = require('fs');
var files = fs.readdirSync('./lib/application/models/');
for (var i in files) {
var definition = require('./application/models/' + files[i]).Model;
console.log('Model Loaded: ' + files[i]);
}
Have you tried the following?
var files = fs.readdirSync(__dirname+'/application/models/');