Has anyone ran the code in npm for slack-wilson lately? It looks like this:
var winston = require('winston'), slackWinston = require('slack-winston').Slack;
var options = {
domain: '<domain>',
token: '<apiToken>',
channel: 'my-sweet-channel',
level: 'warn'
}
winston.add(slackWinston, options);
Then I try this:
winston.log('warn', 'Node test');
For some reason, I just can't get this to send messages to Slack. Am I missing something?
You're not missing anything but the package that you've used is out of date. I recommend you this other package winston-slacker
Related
Preamble
To start off, I'm not a developer; I'm just an analyst / product owner with time on their hands. While my team's actual developers have been busy finishing off projects before year-end I've been attempting to put together a very basic API server in Node.js for something we will look at next year.
I used Swagger to build an API spec and then used the Swagger code generator to get a basic Node.js server. The full code is near the bottom of this question.
The Problem
I'm coming across an issue when writing out to a log file using the fs module. I know that the ENOENT error is usually down to just specifying a path incorrectly, but the behaviour doesn't occur when I comment out the Swagger portion of the automatically generated code. (I took the logging code directly out of another tool I built in Node.js, so I'm fairly confident in that portion at least...)
When executing npm start, a few debugging items write to the console:
"Node Server Starting......
Current Directory:/mnt/c/Users/USER/Repositories/PROJECT/api
Trying to log data now!
Mock mode: disabled
PostgreSQL Pool created successfully
Your server is listening on port 3100 (http://localhost:3100)
Swagger-ui is available on http://localhost:3100/docs"
but then fs throws an ENOENT error:
events.js:174
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open '../logs/logEvents2021-12-24.log'
Emitted 'error' event at:
at lazyFs.open (internal/fs/streams.js:277:12)
at FSReqWrap.args [as oncomplete] (fs.js:140:20)
Investigating
Now normally, from what I understand, this would just mean I've got the paths wrong. However, the file has actually been created and the first line of the log file has been written just fine
My next thought was that I must've set the fs flags incorrectly, but it was set to 'a' for append:
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
Removing Swagger Code
Now here's the weird bit: if I remove the Swagger code, the log files write out just fine and I don't get the fs exception!
This is the specific Swagger code:
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
When I comment out this code, the log file writes out just fine.
The only thing I can think that might be happening is that somehow Swagger is modifying (?) the app's working directory so that fs no longer finds the same file?
Full Code
'use strict';
var path = require('path');
var fs = require('fs');
var http = require('http');
var oas3Tools = require('oas3-tools');
var serverPort = 3100;
// I am specifically tried using path.join that I found when investigating this issue, and referencing the app path, but to no avail
const __logdir = path.join(__dirname,'./logs');
//These are date and time functions I use to add timestamps to the logs
function dateNow(){
var dateNow = new Date().toISOString().slice(0,10).toString();
return dateNow
}
function rightNow(){
var timeNow = new Date().toTimeString().slice(0,8).toString();
return "["+timeNow+"] "
};
console.info("Node Server Starting......");
console.info("Current Directory: " + __dirname)
// Here I create the WriteStreams
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
var errorsFile = fs.createWriteStream(__logdir+"/errorEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Error Log File to location: %s \nWith error description: %s',__logdir, err);
});
// And create an additional console to write data out:
const Console = require('console').Console;
var logOut = new Console(logsFile,errorsFile);
console.info("Trying to log data now!") // Debugging logging
logOut.log("========== Server Startup Initiated ==========");
logOut.log(rightNow() + "Server Directory: "+ __dirname);
logOut.log(rightNow() + "Logs directory: "+__logdir);
// Here is the Swagger portion that seems to create the behaviour.
// It is unedited from the Swagger Code-Gen tool
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
In case it helps, this is the project's file structure . I am running this project within a WSL instance in VSCode on Windows, same as I have with other projects using fs.
Is anyone able to help me understand why fs can write the first log line but then break once the Swagger code gets going? Have I done something incredibly stupid?
Appreciate the help, thanks!
Edit: Tried to fix broken images.
Found the problem with some help from a friend. The issue boiled down to a lack of understanding of how the Swagger module works in the background, so this will likely be eye-rollingly obvious to most, but keeping this post around in case anyone else comes across this down the line.
So it seems that as part of the Swagger initialisation, any scripts within the utils folder will also be executed. I would not have picked up on this if it wasn't pointed out to me that in the middle of the console output there was a reference to some PostgreSQL code, even though I had taken all reference to it out of the main index.js file.
That's when I realised that the error wasn't actually being generated from the code posted above: it was being thrown from to that folder.
So I guess the answer is don't add stuff to the utils folder, but if you do, always add a bunch of console logging...
I'm trying to get a Parse server up and running locally. I'm following the readme that tells me to install parse-server and mongodb, then I run:
parse-server --appId {app_id} --masterKey {key} --databaseURI mongodb://localhost/test
When I try to hit my Parse app locally, with the url http://localhost:1337/parse, calling the foo function, I get this response in my terminal
error: Error handling request: ParseError { code: 141, message: 'Invalid function: "foo"' } code=141, message=Invalid function: "foo"
error: Invalid function: "foo" code=141, message=Invalid function: "foo"
foo is defined in main.js as:
Parse.Cloud.define('foo', function(request, resposne) {
response.success("hi");
});
It's called from my objc code as
[PFCloud callFunctionInBackground:#"foo" withParameters:nil block:^(NSString *res, NSError *error) {
if (error) {
NSLog([error description]);
} else {
NSLog(res);
}
}];
I'm also not able to call other functions in this code that I know work and are present. The issue seems to be not being able to locate the Parse server locally
Not quite sure what I'm doing wrong here, would love some help.
You need to specify a cloud function directory. For example, './cloud/main.js'
I'm not sure how to do that in command line, should be something like --cloud ./cloud/main.js
In your index.js file, it should look like this:
var api = new ParseServer({
databaseURI: 'mongodb://....',
cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js',
appId: process.env.APP_ID || '***',
masterKey: process.env.MASTER_KEY || '***',
serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse'
});
And you can run node index.js to start server locally.
I am trying to connect to OriendDB(v2.0.13) using Orientjs(v2.0.0) on NodeJS(v0.12.2) like so:
var OrientDB = require('orientjs');
var orientDBServer = OrientDB({
host: 'localhost',
port: 2424,
username: 'orientdb',
password: 'orientdb'
});
var database = orientDBServer.use({
name: 'thermos',
username: 'orientdb',
password: 'orientdb'
});
As soon as I make a query, for example:
database.select().from('OUser').all()
.then(function(result) {
console.log(result);
});
I'm getting this error.
Unhandled rejection OrientDB.ConnectionError [1]: Remote server closed
the connection.
at Connection.handleSocketEnd (/usr/share/adafruit/webide/repositories/my-pi-projects/Thermostat/node_modules/orientjs/lib/transport/binary/connection.js:320:9)
at Socket.emit (events.js:104:17)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
I tried different query just to make sure I'm not doing a mistake myself and I also tried via studio and the console directly on the server which worked fine. (using the same logins...)
What can possibly cause this error?
Thanks
Update
I made a second nodejs server and now I can successully make requests on the database that is installed on the first server. I'll investigate if there is some sort of weird permission that blocks localhost or if node is missing some kind of permission...(first server is running raspbian)
I don't think you have to specify the username and password again for the use function. My database config file looks like this and it works like a charm :
var OrientDB = require('orientjs');
var server = OrientDB({
host:'localhost',
port:2424,
username: 'root',
password: 'root'
});
module.exports = server.use('databaseName');
Also, make sure that you created the database with the account you are using. Otherwise, it won't work.
If this still doesn't work, it could be a bug. I would personally try recreating the database...
After days of running in circles I finally found that if I remove another library that I am using, everything works fine... (library causing the conflict is GrovePi). I'll continue investigating to find the root of the issue. Thanks for your help Alex.
How can I update log file when using Winston to handle logging for node.js. Below is the code which I tried. Only first time the data is getting saved in log file.
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: '2012-07-09.log' })
]
});
logger.log('info', 'Test Log Message', { anything: 'This is metadata' });
Im using Node version 0.10.10 and winston 0.7.1
Any help on this will be really helpful. Thanks
Update to winston 7.2
https://github.com/mozilla/persona/commit/ecd695c52d9edbfa46b710ec8832c9fdf890ae16
I use 0.10.24 .It works for me now
I'm reading "Beginning Mobile Application Development in the Cloud" by Richard Rodger and some sample codes use Connect which, I have found, no longer allows direct request processing to the router layer. Here is a sample that gives a 'has no method router' error:
var common = require('./common.js');
var util = common.util;
var connect = common.connect;
var mongo = common.mongo;
var server = connect.createServer(
connect.router(function(app){ //gives the error: "has no method 'router'
// POST {id:<string>}
app.post('/todo/stats/init',function(req,res,next){
common.readjson(req,function(json){
common.sendjson(res,{ok:true,id:json.id});
})
})
// POST {time:<UTC-millis>,total:<todos>,done:<done todos>}
app.post('/todo/stats/collect/:id',function(req,res,next){
var id = req.params.id;
common.sendjson(res,{ok:true,id:id});
common.readjson(req);
})
})
);
mongo.init('todo','localhost');
mongo.open()
server.listen(3000);
Most of the books about node include code that doesn't work and it is very frustrating for someone who begins now to learn and un-learn a minute later. Open Source framework undergoes amazingly fast changes! I just need to learn how to do this the right way. Any thoughts?
Is it right like that?
var common = require('./common.js');
var util = common.util;
var connect = common.connect;
var mongo = common.mongo;
connect.createServer(function (req, res, next) {
app.post('/todo/stats/init',function(req,res,next){
common.readjson(req,function(json){
common.sendjson(res,{ok:true,id:json.id});
})
})
app.post('/todo/stats/collect/:id',function(req,res,next){
var id = req.params.id;
common.sendjson(res,{ok:true,id:id});
common.readjson(req);
})
mongo.init('todo','localhost');
mongo.open();
}).listen(3000);
The connect module you had installed are the newest than the book.
Try sollution from this blog: http://blog.riff.org/2012_04_09_missing_the_connect_router_middleware_for_nodejs
or use connect-router module by run command: npm install connect-route
or clone from github: git clone git://github.com/baryshev/connect-route.git into your node_module directory then do install by: cd connect-route --> npm install -d