Update: I was able to find the error in my code. The problem was that I didn't close my opening parenthesis with closing ones in my console.log for my notes.js.
I started a course on node.js and I am learning how to call other functions created from files on my local system. I have the directory node-notes in which I have two javascript files, app.js and notes.js. I am calling my notes.js in my app.js. I made a simple console.log() call just to make sure its working right in my notes.js. But when I try to run my code using the command node app.js I am getting the error below.
Update: I am using Node 10.0.0
I have no idea what this means so can someone please explain what the error is and how I can fix it. Below I will post both codes for my app.js and notes.js
app.js
console.log("STARTING app.js")
// calling modules using require
// calling functions in fs module and putting in the
// variable fs
const fs = require('fs');
const os = require('os');
const notes = require('./notes.js');
var user = os.userInfo();
console.log(user);
fs.appendFile('greetings.txt', 'Hello World!' + user.username , function(err){
if(err){
console.log("There was an error")
}else{
console.log("It was successful")
}
});
notes.js
console.log("Calling notes.js")
In notes.js you are missing a " to end the string.
console.log("Calling notes.js) should be console.log("Calling notes.js")
Thus you get a SyntaxError: Invalid or unexpected token
Related
there! I am developing app with Next js. and i need to run php script to get some value.
For executing php code I use '"exec-php' package from npm. this package requires enter php file path to js function. But when I put path as parameter to function and call this function, next js throws error - unhandledRejection: Error: File './script.php' not found.
execPhp('./script.php', (err, php, out) => {
php.test(obj, process.env.KEY, (err, result, output, printed) => {
signature = result;
});
});
If you have idea how to solve please answer. Thanks~
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 have a few google cloud functions which make use of the redis memory store and it gives me this Redis connection to :6379 failed - read ECONNRESET at TCP. onread error every time any of function deployed. Previously I shared the createClient() code with all of the functions by creating a separate util file and including them on the CFs, I thought that was the issue. But please note that this Redis cache is working as expected other than this error.
Then I tried putting util code inside each of the google cloud functions which use the redis client to create the client. But I'm still getting this error from every cloud functions when every I deploy any of a cloud function. Even when deploying the functions that do not use the redis.
Here's how I create a client :
const bluebird = require('bluebird');
const redis = bluebird.promisifyAll(require('redis'));
const cache = redis.createClient({ port: REDIS_PORT, host: REDIS_HOST });
cache.on("error", (err) => {
console.log("API One - Redis cache error : " + err);
});
const list = async(data) => {
// Do something with data.
let cachedData;
if(cache.connected) {
await cache.hgetAsync(key); // Get cached Data.
}
// Do something with cached data if cachedData available.
if(cache.connected) {
await cache.hsetAsync(key, data); // Set Some Data.
}
return data;
}
module.exports = functions.https.onCall(list);
Why I'm seeing this error on every cloud function logs?
Sample error logs I get:
API One - Redis cache error : Error: Redis connection to <Ip Address>:6379 failed - read ECONNRESET
API Two - Redis cache error : Error: Redis connection to <Ip Address>:6379 failed - read ECONNRESET
Have you tried closing the redis connection before the function finishes?
The redis module may have background callbacks active during the life of the client, not closing the connection prior to function termination may be causing the connection to timeout when the cloud function terminates. Make sure that all asynchronous operations finish before the function terminates.
For example:
Example
Let me know if this works for you.
I am using the fs.writeFile method in the following way:
fs = require('fs');
fs.writeFile('message.txt', 'Hello Node.js', (err) => {
console.log('It\'s saved!');
fs.readFile('message.txt', function (data) {
console.log("Asynchronous read: " + data.toString());
});
});
output:
It's saved!
Asynchronous read: Hello Node.js
Since I receive the expected output, I assume that the file message.txt is created somewhere, and I am actually writing and reading to/from it. But I can not find it anywhere on my system. So where is message.txt created?
I am using Meteor.js
I found the file by using the command process.cwd() in my console.
Since I am using Meteor.js, the file is saved on default to:
../.meteor/local/build/programs/server
I'm grunt beginner. But whenever I install any kind of grunt library to handle images it does not work.
grunt-webshot, webshot, getPixels, node-image, node, gm, node-pngjs, imagemagick, node-png, png, get-pixels
grunt.registerTask("getPixels", "your description", function() {
var fs = require('fs') , gm = require('gm');
gm('source/templates/t1/images/menu_item_bg.png').size(function (err, size) {
grunt.log.writeln(size.width > size.height ? 'wider' : 'taller than you');
});
});
Silently fails. No error, no nothing (I get: Done, without errors). Does not enter callback.
Same is with other libraries I used.
Only grunt modules can be used in grunt? Dont Think so, it seems i can use any library by using require() and it should work. It works ok with require('path')
Any way I can debug it? Make it return some kind of error or fix this problem?
Edit
I wrote a makescreenshot.js script which I call with node
var webshot = require('webshot');
// also tried commented varians:
//webshot('google.com', 'google.jpg', function(err) {
//webshot('http://google.com', 'google.jpg', function(err) {
webshot('http://google.com', 'google.jpg', {}, function(err) {
console.log('console.log ERROR: ' + err);
});
It returns the following: console.log ERROR: Error: PhantomJS exited with return value 1
Seems I figured it somehow. The problem seemed to be not properly installed Microsoft Visual Studio I reinstalled MSVS 2013 Express and it started taking screens normally.