Error: EACCES: permission denied, open .audit.json - node.js

I was trying to implement the winston logger along with winston-daily-rotate-file in my angular application with node.js.
code worked fine in local windows environment, but while i was moving to higher env in linux, I am getting the below permission error while starting my application by executing "node server.js"
Please help whether issue is with permission or something else
'[FileStreamRotator] Failed to store log audit at:' '//.audit.json' 'Error:' { Error: EACCES: permission denied, open '//.audit.json'
at Object.fs.openSync (fs.js:646:18)
at Object.fs.writeFileSync (fs.js:1299:33)
at Object.FileStreamRotator.writeAuditLog (/apps/app/node_modules/file-stream-rotator/FileStreamRotator.js:244:12)
at Object.FileStreamRotator.addLogToAudit (/apps/app/node_modules/file-stream-rotator/FileStreamRotator.js:318:27)
at EventEmitter.<anonymous> (/apps/app/node_modules/file-stream-rotator/FileStreamRotator.js:432:34)
at emitOne (events.js:116:13)
at EventEmitter.emit (events.js:211:7)
at /apps/app/node_modules/file-stream-rotator/FileStreamRotator.js:478:20
at _combinedTickCallback (internal/process/next_tick.js:131:7)
at process._tickCallback (internal/process/next_tick.js:180:9)
errno: -13,
code: 'EACCES',
syscall: 'open',
path: '//.audit.json' }
part of Server.js
const winston = require('winston');
const winstonRotator = require('winston-daily-rotate-file');
const { combine, timestamp, label, printf } = winston.format;
var rotatorOptions = {
level: 'info',
filename: './logs/app-%DATE%.log',
datePattern: 'MM-DD-YYYY',
handleExceptions: true,
zippedArchive: false,
maxsize: '10m',
maxFiles: '15d',
};
const logger =winston.createLogger({
format: combine(
label({ label: 'APP' }),
timestamp(),
printf(info => {return `${info.timestamp} [${info.label}] ${info.level}:
${info.message}`; })
),
'transports': [ new winstonRotator(rotatorOptions) ]
});
OS : Red Hat Enterprise Linux Server release 7.5 (Maipo)

Related

spawn cd ENOENT

I am building a command line package.
I am using the spawn method to execute cd command.
Here's the code:
const cdChild = spawn('cd', [projectName])
cdChild.stdout.on('data', (data) => {
console.log(data.toString())
})
cdChild.on('error', (err) => {
console.log(err)
})
It gives the following error:
Error: spawn cd ENOENT
at Process.ChildProcess._handle.onexit (node:internal/child_process:282:19)
at onErrorNT (node:internal/child_process:477:16)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -4058,
code: 'ENOENT',
syscall: 'spawn cd',
path: 'cd',
spawnargs: [ 'bruh' ]
}
OS: Windows 10 21H1
Node: v16.13.0

sp-request : trying get file details from sharepoint returns ECONNREFUSED

I have the following code that successfully uploads test.sspkg to my sharepoint app catalog. Now I'm trying to use sp-request to prove that it's actually there.
But I'm getting an ECONNREFUSED error.
Error message
This shows the error:
[14:24:15] INFO: Checking if file (test.sppkg) is checked out
[14:24:15] INFO: File checkout type: 0
[14:24:17] Published file 1482ms
[14:24:17] And we're done...
trying to retrieve: https://mytenant.sharepoint.com/sites/JJTest/_api/web/GetFileByServerRelativeUrl(#FileUrl)/$value?#FileUrl='%2Fsites%2FJJTest%2FAppCatalog%2Ftest.sppkg'
errored out
{ GotError: connect ECONNREFUSED 127.0.0.1:443
at onError (/src/myplugins/node_modules/got/dist/source/request-as-event-emitter.js:140:29)
at ClientRequest.request.on.error (/src/myplugins/node_modules/got/dist/source/request-as-event-emitter.js:157:17)
at ClientRequest.emit (events.js:203:15)
at ClientRequest.EventEmitter.emit (domain.js:448:20)
at ClientRequest.origin.emit.args (/src/myplugins/node_modules/#szmarczak/http-timer/dist/source/index.js:43:20)
at TLSSocket.socketErrorListener (_http_client.js:401:9)
at TLSSocket.emit (events.js:198:13)
at TLSSocket.EventEmitter.emit (domain.js:448:20)
at emitErrorNT (internal/streams/destroy.js:91:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:63:19)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1107:14) name: 'RequestError', code: 'ECONNREFUSED' }
Package
This is the node package I'm using to call the SP API:
"dependencies": {
"sp-request": "^3.0.0"
}
Code:
const sprequest = require('sp-request');
await new Promise((resolve, reject) => {
gulp
.src(folderLocation)
.pipe(
spsync({
username: uname,
password: pwd,
site: siteCatalogUrl + "/",
libraryPath: catalogName,
publish: true,
verbose: true
}))
.on("finish", () => {
var spr = sprequest.create({ username: uname, password: pwd });
//https://mytenant.sharepoint.com/sites/JJTest/_api/web/getFileByServerRelativeUrl('/sites/JJTest/AppCatalog/test.sppkg')
var filepath = `${siteCatalogUrl}/_api/web/GetFileByServerRelativeUrl(#FileUrl)/$value?#FileUrl='${encodeURIComponent("/sites/JJTest/AppCatalog/test.sppkg")}'`;
console.log('trying to retrieve: ' + filepath);
var retrieveFileUrl = filepath;
spr.get(filepath, {
encoding:null
})
.then(data => {
expect(fileContent.equals(data.body)).is.true;
resolve();
})
.catch(data => {
console.log('errored out')
console.log(data)
reject();
});
resolve();
});
});
What I've tried:
I have tried just copying parts of the output from my console directly into the browser. Specifically, this is the output i get from my debug print statement:
trying to retrieve: https://mytenant.sharepoint.com/sites/JJTest/_api/web/GetFileByServerRelativeUrl/(#FileUrl)/$value?#FileUrl='%2Fsites%2FJJTest%2FAppCatalog%2Ftest.sppkg'
errored out
Pasting this:
https://mytenant.sharepoint.com/sites/JJTest/_api/web/GetFileByServerRelativeUrl('/sites/JJTest/AppCatalog/test.sppkg')
into a browser as the URL works. It returns the details of the file to me.
Can you tell me where I've gone wrong? maybe the syntax of substituting the #FileUrl?
I am using gulp version 3.9.1. And I just did a install latest of chai and sp-request.
But tried changing the specific versions to:
"sp-request": "^2.1.3"
"gulp": "^3.9.1",
"gulp-spsync-creds": "2.3.8",
"chai": "3.5.0"
And now, it's happy! it worked!

Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed with Winston

I am getting an error with winston logging if I am using winston-daily-rotate-file.
When I am building my application with webpack there are no errors but when I execute my build below error is coming(stack Trace):
/app/web-app/server/node_modules/winston/lib/winston/logger.js:307
throw ex;
^
Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed
at doWrite (_stream_writable.js:399:19)
at writeOrBuffer (_stream_writable.js:387:5)
at WriteStream.Writable.write (_stream_writable.js:318:11)
at Object.<anonymous> (/mnt/e/workspace/codebase/hermes_dashboard/app/web-app/server/node_modules/file-stream-rotator/FileStreamRotator.js:616:26)
at DailyRotateFile.log (/mnt/e/workspace/codebase/hermes_dashboard/app/web-app/server/node_modules/winston-daily-rotate-file/daily-rotate-file.js:157:20)
at DailyRotateFile._write (/mnt/e/workspace/codebase/hermes_dashboard/app/web-app/server/node_modules/winston-transport/index.js:82:19)
at doWrite (/mnt/e/workspace/codebase/hermes_dashboard/app/web-app/server/node_modules/winston-transport/node_modules/readable-stream/lib/_stream_writable.js:428:64)
at writeOrBuffer (/mnt/e/workspace/codebase/hermes_dashboard/app/web-app/server/node_modules/winston-transport/node_modules/readable-stream/lib/_stream_writable.js:417:5)
at DailyRotateFile.Writable.write (/mnt/e/workspace/codebase/hermes_dashboard/app/web-app/server/node_modules/winston-transport/node_modules/readable-stream/lib/_stream_writable.js:334:11)
at DerivedLogger.ondata (/mnt/e/workspace/codebase/hermes_dashboard/app/web-app/server/node_modules/winston/node_modules/readable-stream/lib/_stream_readable.js:681:20)
at DerivedLogger.emit (events.js:327:22)
My winston config is:
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
var options = {
file: {
zippedArchive: true,
prettyPrint: true,
json: false,
filename: `/app/web-app/server/logs/server_logs/server.log`,
datePattern: '.yyyy-MM-dd',
handleExceptions: true,
maxsize: '10m', // 10MB
maxFiles: 5,
colorize: false,
},
console: {
level: 'debug',
prettyPrint: true,
handleExceptions: true,
json: false,
colorize: true,
},
};
var logger = new winston.createLogger({
transports: [
// new winston.transports.DailyRotateFile(options.file),
new DailyRotateFile(options.file),
new winston.transports.Console(options.console),
],
exitOnError: false, // do not exit on handled exceptions
});
logger.stream = {
write: message => {
logger.info(message);
},
};
module.exports = logger;
I had the exact same error, line number and everything, happening on aws elasticbeanstalk.
It worked locally, but when it got to aws, the error happened because node is running as user 'webapp'. It looks like that user doesn't have permission to write files to /var/log, which seems odd. So I changed it to log to /tmp and the error went away. Note: be sure the log files are owned by webapp (or whatever user runs the node app) or the error will persist.
In my case the directory the logs were supposed to be saved to didn't exist and that was causing the error.

Error after update winston to version 3.2.1. TypeError: self._addDefaultMeta is not a function

After I updated winston to version 3.2.1, I get an error while trying to hot recompile the project (when my project is started and I make changes).
I tried to update all my dependencies to the latest versions, but this did't help.
It seems webpack-hot-middleware doesn't work correctly with the latest version of winston.
I would be grateful for advice on how to fix this.
Error:
i 「wdm」: Compiling...
D:\Dev\MyProjectName\node_modules\winston\lib\winston\create-logger.js:80
self._addDefaultMeta(info);
^
TypeError: self._addDefaultMeta is not a function
at Object.DerivedLogger.<computed> [as log] (D:\Dev\MyProjectName\node_modules\winston\lib\winston\create-logger.js:80:14)
at onInvalid (D:\Dev\MyProjectName\node_modules\webpack-hot-middleware\middleware.js:27:24)
at SyncHook.eval [as call] (eval at create (D:\Dev\MyProjectName\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:9:1)
at SyncHook.lazyCompileHook (D:\Dev\MyProjectName\node_modules\tapable\lib\Hook.js:154:20)
at Watchpack.<anonymous> (D:\Dev\MyProjectName\node_modules\webpack\lib\Watching.js:142:33)
at Object.onceWrapper (events.js:300:26)
at Watchpack.emit (events.js:210:5)
at Watchpack._onChange (D:\Dev\MyProjectName\node_modules\watchpack\lib\watchpack.js:118:7)
at Watchpack.<anonymous> (D:\Dev\MyProjectName\node_modules\watchpack\lib\watchpack.js:99:8)
at Watcher.emit (events.js:210:5)
at D:\Dev\MyProjectName\node_modules\watchpack\lib\DirectoryWatcher.js:101:9
at Array.forEach (<anonymous>)
at DirectoryWatcher.setFileTime (D:\Dev\MyProjectName\node_modules\watchpack\lib\DirectoryWatcher.js:99:42)
at DirectoryWatcher.<anonymous> (D:\Dev\MyProjectName\node_modules\watchpack\lib\DirectoryWatcher.js:312:12)
at D:\Dev\MyProjectName\node_modules\graceful-fs\polyfills.js:285:20
at FSReqCallback.oncomplete (fs.js:159:5)
Logger config:
const winston = require('winston');
const transports = [];
const alignColorsAndTime = winston.format.combine(
winston.format.timestamp({
format: 'HH:MM:ss:SS DD.MM.YY',
}),
winston.format.printf(
info => `${info.timestamp} ${info.level}:${info.message}`,
),
);
/**
* Console transporter
*/
transports.push(new winston.transports.Console({
level: config.logging.console.level,
}));
const logger = winston.createLogger({
level: 'debug',
transports,
format: winston.format.combine(winston.format.colorize(), alignColorsAndTime),
exitOnError: false,
});
module.exports = logger;
Dependency versions:
winston#3.2.1
webpack-hot-middleware#2.25.0
webpack#4.41.2
Check this thread for solution.
https://github.com/winstonjs/winston/issues/1591
bind logger back explicitly to its methods
ex:
const logger = winston.createLogger({
transports: [
new winston.transports.Console()
]
});
logger.info.bind(logger)

AWS Lambda external URI request error: connect ETIMEDOUT

I coded in my local dev environment a node.js function that does several requests to an external url-uri (asynchronously using bluebird and request-promise). It works fine, the function gets the results and save the information into the EC3 database.
The problem comes when I deploy the code (node modules included), and execute it. It has access to the database, but when tries to access to external url-uri the 'request-promise' module gets an 'connect ETIMEDOUT' error.
I did all the AWS indicates to get it, and read and try a all the solutions I found in Stackoverflow, but still having the problem.
https://www.youtube.com/watch?v=AR1nt3iGR5o
The related role that runs the function has the following policies:
AWSLambdaFullAccess - AWSCodeDeployRoleForLambda - AmazonVPCFullAccess - AWSLambdaExecute - AWSLambdaBasicExecutionRole - AWSLambdaVPCAccessExecutionRole - AWSLambdaRole - oneClick_lambda_basic_execution_1535968782861
Function Network Config
Nat getway
Route Table
Could you help me please, or at least give a hint, please?
CODE:
const Promise = require('bluebird');
const Rp = require('request-promise');
const http = require('http');
var httpAgent = new http.Agent();
httpAgent.maxSockets = 15;
var promises = urls.map(function(url){
return Rp({uri: url.url, pool:httpAgent}).then(function(result){
url.result = result;
// Saving space
delete url.url;
return url;
})
});
Promise.all(promises).then(function(results){
return(processResults(results));
}).catch(Error, function (e) {
console.error("Error doing Request: ", e);
}).error(function (e) {
console.error("Unable get info: ", e);
}).then(function(results){
try{
product.callback(results);
}catch (exception) {
console.error('Error callback: ',exception);
}
}).then(function(){
product.finally();
});
ERROR:
2018-09-28T14:53:48.989Z efb5493a-c32d-11e8-ae42-f73dec33ca2a Error doing Request: { RequestError: Error: connect ETIMEDOUT 147.83.184.65:80
at new RequestError (/var/task/node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (/var/task/node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (/var/task/node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (/var/task/node_modules/request/request.js:185:22)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at Request.onRequestError (/var/task/node_modules/request/request.js:881:8)
at emitOne (events.js:116:13)
at ClientRequest.emit (events.js:211:7)
at Socket.socketErrorListener (_http_client.js:387:9)
at emitOne (events.js:116:13)
at Socket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
name: 'RequestError',
message: 'Error: connect ETIMEDOUT 147.83.184.65:80',
cause:
{ Error: connect ETIMEDOUT 147.83.184.65:80
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '147.83.184.65',
port: 80 },
error:
{ Error: connect ETIMEDOUT 147.83.184.65:80
at Object._errnoException (util.js:1022:11)
at _exceptionWithHostPort (util.js:1044:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1198:14)
code: 'ETIMEDOUT',
errno: 'ETIMEDOUT',
syscall: 'connect',
address: '147.83.184.65',
port: 80 },
options:
{ uri: 'http://geoserver.hydsdev.net/geoserver/mhews/wms?SERVICE=WMS&VERSION=1.1.1&REQUEST=GetFeatureInfo&FORMAT=image%2Fjpeg&TRANSPARENT=true&INFO_FORMAT=text%2Fxml&FEATURE_COUNT=50&X=50&Y=50&SRS=EPSG%3A4326&WIDTH=101&HEIGHT=101&QUERY_LAYERS=mhews:ffews_rain_accumulation_15min_opera&LAYERS=mhews:ffews_rain_accumulation_15min_opera&BBOX=0.6319608%2C42.770155%2C0.8319608%2C42.870155000000004&TIME=2018-09-28T17:30:00.000Z',
pool:
Agent {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: [Object],
requests: {},
sockets: {},
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: 15,
maxFreeSockets: 256,
'http:': [Object] },
callback: [Function: RP$callback],
transform: undefined,
simple: true,
resolveWithFullResponse: false,
transform2xxOnly: false },
response: undefined }
Cheers.
Finally I fixed the problem. Don't know why but into 'request-promise' options object I have to put: headers: {'User-Agent':'request' } . Thank you very much #Rajesh!

Resources