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~
Related
When I have an Error in my code, compiling with ts-node, the error does not appear in the console.
For exemple:let data = await fs.readFileSync(path);
I have this code where I use "fs" to read a file, using a path that the function receive as parameter. But when the path is from a file that does not exists nothing happends in the console. The only thing that happens is that the requisition never finish loading.
If I put a console.log like this in the code, the error appears saying that the file does not exists : console.log(fs.readFile(path, (data) => { }))
It doesn't make sense, since the errors are supposed to show in the console. (This happens with lot of type of commum errors that make it harder to finish the application)
here's the repository with all the code https://github.com/Macintosh-1984/Pokedex_Express
somebody help please
You are not capture the error on readFile
fs.readFile(path, 'utf8', function(err, data){
// you have err here
});
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...
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
I am building a web app that allows users to type in phone numbers and send text messages via the Twilio API. I've built the functionality in a file, shown below. If I cd to this file and run node twilioActions.js, the text message gets sent.
var client = require('twilio')(CLIENT_ID, CLIENT_SECRET);
// ideally, I'd like to send the message using this method and call this from other JavaScript files
export const sendMessage = () => {
}
// the following code works when I run 'node twilioActions.js'
client.sendMessage({
to:'...',
from: '...',
body: 'Text message test.'
}, function(err, responseData) {
if (!err) {
console.log(responseData.from); // outputs "+14506667788"
console.log(responseData.body); // outputs "word to your mother."
}
});
However, I want to call the sendMessage method from a different React file. Here is it:
import * as twilioActions from './twilioActions';
class PhoneView extends React.Component{
// other methods are hidden obviously, the one below is called when a button is pressed to send a message.
sendMessage() {
twilioActions.sendMessage();
}
}
When I try to build the project, I get the following errors:
ERROR in ./~/twilio/package.json
Module parse failed:/Users/Felix/Desktop/ECE590/node_modules/twilio/package.json Line 2: Unexpected token :
You may need an appropriate loader to handle this file type.
| {
| "_args": [
| [
| "twilio",
# ./~/twilio/lib/Client.js 5:17-43
ERROR in ./~/request/lib/har.js
Module not found: Error: Cannot resolve module 'fs' in /Users/Felix/Desktop/ECE590/node_modules/request/lib
# ./~/request/lib/har.js 3:9-22
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'net' in /Users/Felix/Desktop/ECE590/node_modules/tunnel-agent
# ./~/tunnel-agent/index.js 3:10-24
ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in /Users/Felix/Desktop/ECE590/node_modules/tunnel-agent
# ./~/tunnel-agent/index.js 4:10-24
I feel like I am making a simple mistake and perhaps am not using the correct libraries or including the proper references. Could someone point me in the right direction about how to get this to work? Thank you so much!
Twilio developer evangelist here.
The twilio npm module is not built or recommended for use in the front end. The main thing is that you would need to expose your account credentials in the front end code of your site. This is a security risk as it means a malicious attacker could get hold of your credentials and abuse your Twilio account.
I recommend creating a service on your server side that you can call to with an AJAX request in order to perform actions like this.
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.