How to set FileType on filestream - javascript

I'm trying to send a file stream from c# to my js backend. The name and path get send over correctly but the type seems to be missing when I log the file that enters my backend and I absolutely need the filetype but I can't figure out how to pass it with. can someone help me with this please?
object that comes in:
File {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
size: 13920,
path: '/var/folders/5g/f343vctd6hd7smyd5ybnfp4m0000gn/T/upload_4aebdbbee06344e12d8566dd706fd1e6',
name: 'Invoice19.pdf',
type: null,
hash: null,
lastModifiedDate: 2020-03-17T14:11:04.812Z,
_writeStream: WriteStream {
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: true,
needDrain: false,
ending: true,
ended: true,
finished: true,
destroyed: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: true,
errorEmitted: false,
emitClose: false,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object]
},
writable: false,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
path: '/var/folders/5g/f343vctd6hd7smyd5ybnfp4m0000gn/T/upload_4aebdbbee06344e12d8566dd706fd1e6',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
autoClose: true,
pos: undefined,
bytesWritten: 13920,
closed: false
}
}
my c# code
public IAsyncResult BeginExecute()
{
// set authentication
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", BearerToken);
string url = "http://12915520.ngrok.io/api/organisations/" + OrganisationId + "/projects/" + ProjectId + "/process";
string response = null;
bool succesfullRequest = false;
try
{
using (FileStream fs = File.Open(#"C:\Users\X Y\Downloads\Invoice19.pdf", FileMode.Open, FileAccess.Read))
{
// send the content to the backend, parse results
HttpContent content = new StreamContent(fs);
MultipartFormDataContent formdata = new MultipartFormDataContent();
formdata.Add(content, "files", "Invoice19.pdf");
var result = client.PostAsync(url, formdata).Result;
response = result.Content.ReadAsStringAsync().Result;
succesfullRequest = result.IsSuccessStatusCode;
}
}
// I absolutely want to catch every exception and pass these along to the workflow
catch (Exception ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
throw;
}
// if something went wrong in the backend, throw an error
if (!succesfullRequest)
{
throw new Exception("Something went wrong during the upload process");
}
UploadResponse r = JsonConvert.DeserializeObject<UploadResponse>(response);
Console.WriteLine("uploadresponse:" + r.ToString());
// dirty solution: since we don't know how long the pipeline needs to process the upload, we'll be polling for a result
// since this is a poc this is a temporary solution, if this gets released this needs to be rewritten (maybe with webhooks)
//var polling = true;
//do
//{
// response = client.GetAsync(url + "/" + r.uploadId).Result.Content.ReadAsStringAsync().Result;
// if (response != "null")
// {
// polling = false;
// }
//} while (polling);
// Because we know that there is a response now, actually execute the request
//return client.GetAsync(url + "/" + r.uploadId);
return null;
}

I believe that you need to change how you are using MultipartFormDataContent()
this works for me
using (var content = new MultipartFormDataContent())
{
content.Add(new StreamContent(stream)
{
Headers =
{
ContentLength = stream.Length,
ContentType = new MediaTypeHeaderValue([your content type])
}
}, "[name ex: file]", "[file name ex: file.jpg]");
}

I got it working by doing this:
MultipartFormDataContent formdata = new MultipartFormDataContent()
foreach (var filePath in Files.Get(context))
{
// create filestream content
FileStream fs = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
HttpContent content = new StreamContent(fs);
string name = GetFileName(filePath);
content.Headers.Add("Content-Type", GetFileType(name));
formdata.Add(content, "files", name);
}
// send content to the backend and parse result
var resultPost = client.PostAsync(url, formdata).Result;
response = resultPost.Content.ReadAsStringAsync().Result;
succesfullRequest = resultPost.IsSuccessStatusCode;
Basically, I set the content type of my inner content to whatever filetype it is and then set the content-type of my outer content to multipart/form-data (by adding it to the MultiPartFormData)
since I only support a limited amount of file types, I was able to write a simple function:
private string GetFileType(string name)
{
char[] charSeparators = new char[] { '.' };
var splitName = name.Split(charSeparators);
string extension = splitName[1].ToLower();
switch (extension)
{
case "pdf":
return "application/pdf";
case "png":
return "image/png";
case "doc":
return "application/msword";
case "docx":
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
case "txt":
return "text/plain";
case "tif":
return "image/tif";
case "jpg":
return "image/jpg";
case "rtf":
return "application/rtf";
// default == not supported type, we don't set content type
default:
return "";
}
}

Related

Got different answer from a return of a function

I'm blocked since few hours now, I wish somebody can help me figure out what I do wrong.
This whole code is to get a json response from an API. I want to understand what are my errors, so please, explain a little ! ;)
const fetch = require('node-fetch');
const Bluebird = require('bluebird');
fetch.Promise = Bluebird;
const xml2js = require('xml2js');
module.exports = {
getImage : async function (tag, random){
let url = "anApiLink" + tag;
if(random != null) url = "anApiLink" + tag + "&id=" + random;
const get_data = async url => {
try {
const response = await fetch(url);
if(! response.ok) return new Error("Erreur lors de la récupération de l'image : " + response.statusText);
const text = await response.text();
const xmlToJson = await xml2js.parseString(text, (err, result) => {
if(err) throw err;
const json = JSON.stringify(result, null, 4);
return json;
});
console.log(xmlToJson);
return xmlToJson;
} catch (err) {
console.error(err);
}
};
return get_data(url);
}
}
My json const is what I want to return from the global function (get_data), and it's an actual good json answer. With my final return, I actually get what's below.
From my console.log() :
{
comment: '',
sgmlDecl: '',
textNode: '',
tagName: '',
doctype: '',
procInstName: '',
procInstBody: '',
entity: '',
attribName: '',
attribValue: '',
cdata: '',
script: '',
c: '',
q: '',
bufferCheckPosition: 65536,
opt: { trim: false, normalize: false, xmlns: false, lowercase: undefined },
looseCase: 'toUpperCase',
tags: [],
sawRoot: false,
closedRoot: false,
closed: false,
error: null,
tag: null,
strict: true,
noscript: true,
state: 0,
strictEntities: undefined,
ENTITIES: {},
attribList: [],
trackPosition: true,
column: 0,
line: 0,
position: 0,
errThrown: false,
onerror: [Function],
onend: [Function],
ended: true,
onopentag: [Function],
onclosetag: [Function],
ontext: [Function],
oncdata: [Function],
startTagPosition: 781
}
Thanks for the help.
Salut, I didn't even realize at first that I was reading french in your code... Your problem seemed to be related to that library you're using, xml2js. I took a look at their docs, and maybe this may help you.
The function itself does not return the result, but you can get it in the callback, that's the reason why you're logging this weird object. You could create a separate var to store the result, but I have a better solution.
If you want to use promises, I found this in the docs, and this in the source code about parseStringPromise, and I think that's what you want. The source code indicates that the result is returned as a Promise here.
In short, what you return in the callback isn't returned by parseString. This is what xmlToJson should be to act as intended.
// Not tested. I might have made an error about the location of 'then', not sure.
const xmlToJson = await xml2js.parseStringPromise(text)
.catch(e => throw e)
.then(r => JSON.stringify(r, null, 4))

Store cirular object in localstorage

I want to store below object into my localstorage and want to use throughout application. For that I used circular function. But when I recreate object from string then it is not same object. Below is my object.
e.exports {client: I}
client: I
browserDetails: {browser: "chrome", version: 80}
permOnClick: true
ringToneFlag: true
ringToneBackFlag: true
connectToneFlag: true
isLoggedIn: true
reconnectInterval: null
reconnectTryCount: 0
localStorage: Storage
length: 13
AsteriskIntegration:ServerIP: ""
auto_saved_sql: "INSERT INTO document_revisions (id,change_log,document_id,doc_id,doc_type,doc_url,date_entered,created_by,filename,file_ext,file_mime_type,revision,deleted,date_modified) VALUES ('e0a40e04-ceb6-dd54-a05d-5e5cc8f4461b','Document Created','390d0e08-1ba9-dcff-1eb8-5e5cc8b83741','','Sugar','','2020-03-02 08:47:40','1','Test.pdf','pdf','application/pdf','1',0,'2020-03-02 08:47:40')"
plivoBrowserSdkJSON: "{"client":{"browserDetails":{"browser":"chrome","version":80},"permOnClick":true,"ringToneFlag":true,"ringToneBackFlag":true,"connectToneFlag":true,"isLoggedIn":true,"reconnectInterval":null,"reconnectTryCount":0,"localStorage":{"AsteriskIntegration:ServerIP":"","endpointID":"001f922acfecfd9498ea0b2b84703ce8f14d2fa55dc96b857bfbfd1ffe9af40d","AsteriskIntegration:Extension":"","AsteriskIntegration:Context":"","AsteriskIntegration:ToggleStatus":"Minimized","AsteriskIntegration:ShowNotification":"0","favorite_tables":"undefined","debug":"","csio_auth_data":"\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWJ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ache":{"credentials":{}},"_configuration":{"authorization_user":"david","password":null,"realm":"phone.plivo.com","ha1":"2291bb7891ceefc3ab2221cb1565fba6","display_name":null,"uri":{"_parameters":{},"_headers":{},"_scheme":"sip","_user":"david5719898358329549231","_host":"phone.plivo.com"},"contact_uri":{"_parameters":{"transport":"ws"},"_headers":{},"_scheme":"sip","_user":"r594n4dv","_host":"aeqf7b88emss.invalid","_port":null},"instance_id":"78fdf100-2c4d-4deb-a8ac-0cee371db730","use_preloaded_route":false,"session_timers":false,"session_timers_refresh_method":"UPDATE","no_answer_timeout":60000,"register":true,"register_expires":120,"registrar_server":{"_parameters":{},"_headers":{},"_scheme":"sip","_user":null,"_host":"phone.plivo.com"},"connection_recovery_max_interval":20,"connection_recovery_min_interval":2,"via_host":"aeqf7b88emss.invalid","user_agent":"plivo-browser-sdk 2.1.20","plivosip_id":"out4c","hostport_params":"phone.plivo.com"},"_dynConfiguration":{"register":true},"_dialogs":{},"_applicants":{},"_sessions":{},"_transport":{"status":0,"socket":{"_url":"wss://phone.plivo.com:5063","_sip_uri":"sip:phone.plivo.com:5063;transport=ws","_via_transport":"WSS","_ws":{}},"sockets":[{"weight":0,"status":0}],"recovery_options":{"max_interval":20,"min_interval":2},"recover_attempts":0,"recovery_timer":null,"close_requested":false},"_contact":{"pub_gruu":null,"temp_gruu":null},"_status":1,"_error":null,"_transactions":{"nist":{},"nict":{},"ist":{},"ict":{}},"_data":{},"_closeTimer":null,"_registrator":{"_expires":120,"_call_id":"vsa32oc37nnu7143rk274o","_cseq":2,"_registrationTimer":131,"_registering":false,"_registered":true,"_contact":"<sip:r594n4dv#aeqf7b88emss.invalid;transport=ws>;+sip.ice;reg-id=1;+sip.instance=\"<urn:uuid:78fdf100-2c4d-4deb-a8ac-0cee371db730>\"","_extraHeaders":[],"_extraContactParams":""}},"_currentSession":null,"callSession":null,"callUUID":null,"callDirection":null,"lastCallUUID":null,"_lastCallSession":null,"incomingInvites":{},"incomingCallsInitiationTime":{},"lastIncomingCall":null,"callStats":{},"sipAuthBy":null,"userName":"david5719898358329549231","options":{"codecs":["OPUS","PCMU"],"enableTracking":true,"debug":"DEBUG","permOnClick":true,"enableIPV6":false,"audioConstraints":{},"dscp":true,"appId":"380077084","appSecret":null,"registrationDomainSocket":null,"clientRegion":null,"preDetectOwa":false,"disableRtpTimeOut":false,"allowMultipleIncomingCalls":false},"callstatskey":null,"rtp_enabled":null,"statsioused":false,"audio":{"ringtoneDevices":{},"microphoneDevices":{},"speakerDevices":{}},"owaLastDetect":{"time":0,"isOneWay":true},"owaDetectTime":3600000,"outBoundConnectionStages":[],"_outboundExtraHeaders":{},"_outboundCallNumber":null,"statsSocket":null,"bucketApiUrl":"https://stats.plivo.com/v1/browser/bucketurl/","bucketApiBody":{"username":"david5719898358329549231","password":"lokesh","domain":"phone.plivo.com"},"remoteView":{"width":0,"height":0},"ringToneView":{},"ringBackToneView":{},"connectToneView":{},"audioDevDic":["{\"deviceId\":\"default\",\"kind\":\"audioinput\",\"label\":\"Default\",\"groupId\":\"4ce38a6beefca1618312cc984683f32afdd8a031f04697ce4606940d6456d61b\"}","{\"deviceId\":\"d07a50eedfb049ab16b39ddbb545865947600d3673194a608af977f9ce1cf21f\",\"kind\":\"audioinput\",\"label\":\"Built-in Audio Analog Stereo\",\"groupId\":\"e8c51c00b437c50e95499ec3af71c3ad64bd7f204ee5dc3723471a9e0b8a5291\"}","{\"deviceId\":\"default\",\"kind\":\"audiooutput\",\"label\":\"Default\",\"groupId\":\"default\"}","{\"deviceId\":\"aef20cba2448b4d804e2e968682a01c4b1940595ca9b65de3acc0e16ea987338\",\"kind\":\"audiooutput\",\"label\":\"Built-in Audio Analog Stereo\",\"groupId\":\"e8c51c00b437c50e95499ec3af71c3ad64bd7f204ee5dc3723471a9e0b8a5291\"}"]}}"
endpointID: "001f922acfecfd9498ea0b2b84703ce8f14d2fa55dc96b857bfbfd1ffe9af40d"
AsteriskIntegration:Extension: ""
AsteriskIntegration:Context: ""
AsteriskIntegration:To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9HV-R7HIKhb_4ZiybW6njYcnqQ""
AsteriskIntegration:UserID: "1"
AsteriskIntegration:SocketPort: ""
__proto__: Storage
_events: {}
_eventsCount: 0
_maxListeners: undefined
phone: e.exports {_events: {…}, _eventsCount: 7, _maxListeners: undefined, _cache: {…}, _configuration: {…}, …}
_currentSession: null
callSession: null
callUUID: null
callDirection: null
lastCallUUID: null
_lastCallSession: null
incomingInvites: Map(0) {}
incomingCallsInitiationTime: Map(0) {}
lastIncomingCall: null
callStats: a {}
sipAuthBy: null
userName: "david5719898358329549231"
options: {codecs: Array(2), enableTracking: true, debug: "DEBUG", permOnClick: true, enableIPV6: false, …}
callstatskey: "73aec46c-4893-41ff-aab9-aa23ef9df7f0"
rtp_enabled: true
statsioused: false
audio: {ringtoneDevices: {…}, microphoneDevices: {…}, speakerDevices: {…}, availableDevices: ƒ, revealAudioDevices: ƒ}
audioConstraints: {}
owaLastDetect: {time: 0, isOneWay: true}
owaDetectTime: 3600000
outBoundConnectionStages: []
_outboundExtraHeaders: {}
_outboundCallNumber: null
statsSocket: s {url: "wss://insights.plivo.com/ws", ws: WebSocket, userName: "david5719898358329549231", callstatskey: "73aec46c-4893-41ff-aab9-aa23ef9df7f0"}
statsCallback: ƒ ()
calcConnStage: ƒ (e)
str: ƒ (e)
bucketApiUrl: URL {href: "https://stats.plivo.com/v1/browser/bucketurl/", origin: "https://stats.plivo.com", protocol: "https:", username: "", password: "", …}
bucketApiBody: {username: "david", password: "abc", domain: "phone.plivo.com"}
remoteView: audio#plivo_webrtc_remoteview
ringToneView: audio#plivo_ringtone
ringBackToneView: audio#plivo_ringbacktone
connectToneView: audio#plivo_connect_tone
audioDevDic: (4) ["{"deviceId":"default","kind":"audioinput","label":…2c403010b9047aa8545d46eda66540c5d9fcd4cec87eb17"}", "{"deviceId":"d07a50eedfb049ab16b39ddbb545865947600…9ef43f5d3efef4e5adabc15779e3ce654fd2ff0ae4c72e7"}", "{"deviceId":"default","kind":"audiooutput","label":"Default","groupId":"default"}", "{"deviceId":"aef20cba2448b4d804e2e968682a01c4b1940…9ef43f5d3efef4e5adabc15779e3ce654fd2ff0ae4c72e7"}"]
plivoSocket: e.exports {_url: "wss://phone.plivo.com:5063", _sip_uri: "sip:phone.plivo.com:5063;transport=ws", _via_transport: "WSS", _ws: WebSocket, onconnect: ƒ, …}
heartbeatTimer: 85
__proto__: o
__proto__: Object
And below is my code to convert object to string.
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
var plivoBrowserSdkJSON = JSON.stringify(plivoBrowserSdk, getCircularReplacer());
I followed below answer.
How can I print a circular structure in a JSON-like format?
// create a class with constructor to reinitialise with the data only
You cant serialise function. Coz it is not enumeration properties
class SomeUtil {
constructor({ statsSocket, remoteView, ringToneView, ...rest }) {
this.statsSocket = statsSocket
this.remoteView = remoteView
this.ringToneView = ringToneView // some customization
Object.entries(rest).forEach(([key, value]) => {
this[key] = value
})
}
statsCallback() {
console.log(1)
}
}
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
seen.add(value);
}
return value;
};
};
// File one
function test1() {
const util = new SomeUtil();
util.remoteView = "audio#plivo_webrtc_remoteview"
const onSave = () => {
localStorage.setItem("SomeUtil", JSON.stringify(util, getCircularReplacer()))
}
}
// File 2
function test3() {
const util = new SomeUtil(localStorage.getItem("SomeUtil"));
console.log(util.remoteView)
}
//

unable to submit message: The path is not of a legal form

I have only frontend code which works with API calls. I need to implement a similar page for photos with changing some parameters like job type, preference name, etc. When I changed job type=2, it always showed this error. I checked API with job type 2 on postman, It is working fine but not in the code and app.so what might be the error.for example,
SendNewJob: function (e) {
e.preventDefault();
$("#inputValidationErrorMessage").hide();
$("#extRefValidationErrorMessage").hide();
var existingToken = IO.LocalStorage.GetValue("userToken");
var frmData1 = new FormData();
var model = {
ThirdPartyClientId: Number($("#thirdPartyUser1").val()) || undefined,
JobType: 2,
Reference: $("#jobRefNr1").val(),
Notes: $("#notes").val(),
ExternalReference: $("#externalRefNr1").val() || undefined,
PreferenceNameId: Number($("#prefernceTypePhoto").val()) || undefined
};
and
service.js file
var ProjectConfigurationLevel =
{
Debug: 0,
Local: 1,
Live: 2
};
var FloorplanType =
{
Sketch: 1,
Draft: 2,
Ammendments: 3,
Final: 4
};
var MessageType =
{
Redirect: 0,
Info: 1,
Warning: 2,
Error: 3
};
var ForFront = {
Config: ProjectConfigurationLevel.Live,
Defaults: {
JobsPageSize: 5,
MaxPagesShown: 5
},
Urls: {
Live: "https://api.xyz.com/",
Debug: "http://test-api.xyz.com/",
Local: "http://192.168.60.75:3000/",
},
Links: {
SketchLocation: function () {
switch (ForFront.Config) {
case ProjectConfigurationLevel.Debug:
return "http://testsite.com/";
case ProjectConfigurationLevel.Local:
return "http://192.168.60.75:3001/";
case ProjectConfigurationLevel.Live:
return "http://testsite.com/";
default:
console.error("unknown config " + ForFront.Config);
break;
}
},
SubmitNewJob: function () {
var endpoint = "v1/Jobs";

MouseEventConstructor is not a constructor

When I execute my tests locally they pass with no problems but when tests proceed on the server I get:
TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown',
EXEC : error : TypeError: MouseEventConstructor is not a constructor (evaluating 'new MouseEvent('mousedown',
{
'which': 1,
'view': window,
'bubbles': true,
'cancelable': true
})')
for the code:
HTMLElement.prototype.mouseDownLeftButton = function () {
var event = new MouseEvent('mousedown',
{
'which': 1,
'view': window,
'bubbles': true,
'cancelable': true
});
this.dispatchEvent(event);
};
which is totally fine. Is there any other way to create a new MouseEvent ?
There is a polyfill from MDN that will resolve the issue:
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/MouseEvent#Polyfill
(function (window) {
try {
new MouseEvent('test');
return false; // No need to polyfill
} catch (e) {
// Need to polyfill - fall through
}
// Polyfills DOM4 MouseEvent
var MouseEvent = function (eventType, params) {
params = params || { bubbles: false, cancelable: false };
var mouseEvent = document.createEvent('MouseEvent');
mouseEvent.initMouseEvent(eventType, params.bubbles, params.cancelable, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
return mouseEvent;
};
MouseEvent.prototype = Event.prototype;
window.MouseEvent = MouseEvent;
})(window);
Most likely your local test infra uses real browser and on server it uses PhantomJS.
The latter still doesn't support new MouseEvent: https://github.com/ariya/phantomjs/issues/11289
I had to do the following trick to make tests pass:
function createMouseEvent(typeArg: string): MouseEvent {
let event = document.createEvent('MouseEvent');
event.initMouseEvent(typeArg,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined,
undefined);
return event;
}

javascript constructor + node js createServer

Im trying to wrap node js server in JS object,
In order to do that, I wrote this constructor:
function staticServerObj (rootFolder) {
this.rootFolder = rootFolder;
this.port = null;
this.isStarted = false;
this.startedData = null;
this.numOfCurrentRequests = 0;
this.numOfAllRequests = 0;
this.numOfSuccesfulRequest = 0;
this.serverObj = net.createServer(function (socket) {
handleNewConnection(this, socket);
});
};
The problem is, in handleNewConnection function, Im trying to use my staticServerObj vars (like: staticServerObj.port) and it's undefined,
Furthermore, when I try to log the server object in that way:
function handleNewConnection(server, socket) {
console.log(server);
}
Im getting this result:
{ domain: null,
_events: { connection: [Function] },
_maxListeners: 10,
_connections: 1,
connections: [Getter/Setter],
_handle:
{ fd: 12,
writeQueueSize: 0,
onconnection: [Function: onconnection],
owner: [Circular] },
_usingSlaves: false,
_slaves: [],
allowHalfOpen: false,
_connectionKey: '4:0.0.0.0:1234' }
Any Ideas?
You have a scoping problem. The this inside your createServer() does not point to the server object anymore. To solve this either save a reference to the staticServerObj like this:
function staticServerObj (rootFolder) {
this.rootFolder = rootFolder;
this.port = null;
this.isStarted = false;
this.startedData = null;
this.numOfCurrentRequests = 0;
this.numOfAllRequests = 0;
this.numOfSuccesfulRequest = 0;
var that = this;
this.serverObj = net.createServer(function (socket) {
handleNewConnection(that, socket);
});
};
or use bind() and have access to the this reference inside your function:
function staticServerObj (rootFolder) {
this.rootFolder = rootFolder;
this.port = null;
this.isStarted = false;
this.startedData = null;
this.numOfCurrentRequests = 0;
this.numOfAllRequests = 0;
this.numOfSuccesfulRequest = 0;
var that = this;
this.serverObj = net.createServer( handleNewConnection.bind( this ) );
};
function handleNewConnection(socket) {
// your former server variable can now be accessed using `this`
console.log( this );
}

Categories