Giter Club home page Giter Club logo

the-nodejs-master-class's People

Contributors

pirple-author avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

the-nodejs-master-class's Issues

API Dockerization

Hi,
This is not an issue but I'm not sure where else should I put this request. Any of you have dockerized the API?

Connect to nexmo api

How can I connect to nexmo SMS API, I have some errors with my code

const https = require('https');
const queryString = require('querystring');

function sendNexmoSms() {
const payload = {
to: '+91...',
from: 'NEXMO',
text: 'HELLO, I AM NEXMO DEMO SMS !'
};
const stringPayload = queryString.stringify(payload);
// console.log(stringPayload);
const requestOptions = {
protocol: 'https:',
hostname: 'rest.nexmo.com',
method: 'POST',
path: '/sms/json',
auth: 'api_key:api_secret',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(stringPayload)
}
};
const req = https.request(requestOptions, res => {
const code = res.statusCode
if (code == 200 || code == 201) {
console.log('DONE');
} else {
console.log('errors happend');
}
});
req.on('error', e => console.log(e));
req.write(stringPayload);
req.end();
}

sendNexmoSms();

callback vs callBack in node.js

how complete the ftruncate ? with/withtout callback(false)?
my code in RESTful API is :

lib.update=function(dir,file,data, callBack){
//Open the file for writing
fs.open(lib.baseDir+dir+'/'+file+'.json', 'r+',function(err,fileDescriptor){
    if(!err && fileDescriptor){
        var stringData = JSON.stringify(data);
        
        fs.ftruncate(fileDescriptor, (err) => {
                if (!err) {
                    fs.writeFile(fileDescriptor, stringData, function (err) {
                        if (!err) {
                            fs.close(fileDescriptor, function (err) {
                                if (!err) {
                                    callBack(true);
                                } else {
                                    callback('Err in closing existing file');
                                }
                            });
                        } else {
                            callback('Error updating to existing file');
                        }
                    });

                } else {
                    callback('Err truncating file');
                }
            });
    } else{
        callBack('Cannot Update the file, it may not exist yet');
    }
});
};

the error is actually, when we run the postman, it is keep sending the 'sending the request' but never ending; but the file is updated

Oh! My goodness !!! I just noticed
have u notice I have written "callback" as "callBack" in 2 place.
and I jst made it as "callback" instead of any caps... after editing 'callback' in fs.open (bottom else for err msg of 'file may not exist yet'), then postman works, file updated. DONE!

Then when I also change the 'callBack' in fs.close (if no err), then it again sending the reuqest, but not even updating...?

Can someone explain the logic here?
Is this matter of NodeJs version ?
Food For Learning

_performance.getEntriesByType is not a function

Thanks for such a great course; I think its one of the best Node courses currently available.

I'm a fan of reading source code unguided and so I have spent some hours going into the FINAL version of the project available in Section 7. The program was bailing out with a silent fatal crash and it took me some time to work out why; in subsequent versions of Node, performance.getEntriesByType was moved to a different css performanceObserverEntryList.getEntriesByType(type) (see v11.x docs).

As this course is still current my suggestion would be to add some Node version checking code that conditionally loads these classes/methods so that other students don't run into the same error. I would be happy to submit a PR with the necessary changes.

Unable to serve static png image

This course is amazing so far and ive learned a very substancial amount, however i have came across one issue that i cannot seen to figure out. Im trying to serve static files like css, js, and a favicon image, but when i try and serve a .png image, it just shows up as a black square, or if referenced in the html dosent show up at all. I sent the image by doing the following:

const http = require("http");
const fs = require("fs");
const server = http.createServer((req,res) => {
fs.readFile("imagePath",(err,imgData) => {
res.setHeader("Content-Type","image/png");
res.end(imgData);
})
});
server.listen(3000);

The path is correct, no error occurs while reading the png file, and i even logged out "err" and "imgData", and they are indeed wht they should be , which is "null" and a buffer. But in the browser it dosent seem to have rendered properly. Dose anyone have a work around or know somthing that im missing?

config server

2 things:
1.
when we have to export config file to index.js, code in config should mention correct module/
in this lecture the export "environmentToExport" does not directly noticed.. as if we use "config" inside index from config.js file, then within the config file there shuold be at least the word "config"
so to export I did: export const config = environmentToExport;

  1. on terminal (my OS is windows), NODE_ENV=staging (or production) does not detect at all... it gives only
    `NODE_ENV=staging node index.js NODE_ENV=staging : The term 'NODE_ENV=staging' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + NODE_ENV=staging node index.js + ~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (NODE_ENV=staging:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException

I tried: $setNODE_ENV="production"` not working???

can someone fix it?

DIfference

In res.end("Hello World\n");
In VS Code this will show Hello World\n in the terminal
In Atom this will show Hello World in the terminal

Unable to perform JSON.parse

const data = {
      trimmedPath: trimmedPath,
      queryStringObject: queryStringObject,
      method: method,
      headers: headers,
      payload: helpers.parseJsonToObject(buffer), // the output is always {}
 };

This happens because in the helpers.js file because

helpers.parseJsonToObject = function (str) {
  try {
    const obj = JSON.parse(str); // It throws an error here
    return obj;
  } catch (e) {
    return {};
  }
};

So I tried console logging the JSON.parse(str) but that also throws an error.
The error message is

undefined:5
    "password: "thisIsNotAPassword",
                ^

SyntaxError: Unexpected token t in JSON at position 100
    at JSON.parse (<anonymous>)
    at Object.helpers.parseJsonToObject (C:\Users\Marshall Shelly\Desktop\app\lib\helpers.js:14:20)
    at IncomingMessage.<anonymous> (C:\Users\Marshall Shelly\Desktop\app\index.js:78:24)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1220:12)
    at processTicksAndRejections (internal/process/task_queues.js:84:21)

I even download the project code from github and tried it, but the same error occured

Please help

Browser/Postman: Your connection is not secure

Anyone else getting the "Your connection is not secure", when using the self-signed certificate?
I know there is is a simple solution to this (adding an exception in the browser, and modifying the postman settings), but since I am the only one having (posting about) this issue, and since it is not mentioned in the course, maybe I got something wrong?

Section3/Storage/lib/data.js

// Delete a file
lib.delete = function(dir,file,callback){
  // Unlink the file
  fs.unlink(lib.baseDir+dir+'/'+file+'.json', function(err){
    if(!err){
      callback(false);
    }else{
      callback(err);
    }
  });
};

delete file code has to be updated

Section 3 Parsing Query String shows a weird queryStringObject

This is code I use (same as in the masterclass, except for the const instead of var)

/*
 * Primary file for the API
 */

// Dependencies
const http = require("http");
const url = require("url");

// The server should respond to all requests with a string
const server = http.createServer(function (req, res) {
  // Get the URL and parse it
  const parsedUrl = url.parse(req.url, true);

  // Get the path
  const path = parsedUrl.pathname;
  const trimmedPath = path.replace(/^\/+|\/+$/g, "");

  // Get the query string as an object
  const queryStringObject = parsedUrl.query;

  // Get the HTTP Method
  const method = req.method.toLowerCase();

  // Send the response
  res.end("Hello World!\n");

  // Log the request path
  console.log(
    "Request received on path: " +
      trimmedPath +
      " with method: " +
      method +
      " and this query string: ",
    queryStringObject
  );
});

// Start the server, and have it to listen on port 3000
server.listen(3000, function () {
  console.log("The server is listening on port 3000 now");
});

Whenever I run the code, and visit the URL http://localhost:3000/foo?fizz=buzz or run cURL on it, I get the console log as Request received on path: foo with method: get and this query string: [Object: null prototype] { fizz: 'buzz' }

Why do I get a [Object: null prototype] inside the log?

SyntaxError: Unexpected token } in JSON

When I create a put operation to update the username of a related phone number, console Throws this error on the parseJsonToObject method:

SyntaxError: Unexpected token } in JSON at position 57
    at JSON.parse (<anonymous>)
    at Object.helpers.parseJsonToObject (../lib/helpers.js:27:20)
    at IncomingMessage.<anonymous> (../index.js:87:24)
    at emitNone (events.js:106:13)
    at IncomingMessage.emit (events.js:208:7)
    at endReadableNT (_stream_readable.js:1064:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)

Returning this 400 {"Error":"Missing required field."}
const data = {
      trimmedPath,
      queryStringObject,
      method,
      headers,
     //This is line 87, buffer carries on data that is being passed through helpers method,
      payload: helpers.parseJsonToObject(buffer),
    };

helpers.parseJsonToObject = function (str) {
  try {
   //But here, the data get lost and JSON.parse Throw above error, so then payload is empty
    let obj = JSON.parse(str);
    return obj;
  } catch (error) {
    console.log(error);
    return {};
  }
};

This behavior is weird because JSON.parse works with other data that is being sent through other operations such as delete, post, get.

has anybody faced this same problem?

Thanks

Callback is not a function

lib.read = function(dir,file,callback){
  fs.readFile(lib.baseDir+dir+'/'+file+'.json', 'utf8', function(err,data){
    callback(err,data);
  });

Here the console is telling

    callback(err,data);
    ^
TypeError: callback is not a function
    at ReadFileContext.callback (C:\Users\.....\Backend\Storing_Data\lib\data.js:48:5)
    at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:273:13)

try catch not working in tests/index.js file

Getting this when running tests:

logs.truncate should not throw if the log id does not exist. It should callback err instead
assert.js:337
throw err;
^

AssertionError [ERR_ASSERTION]: The expression evaluated to a falsy value:

assert.ok(logFileNames.length > 1)

Instead the thrown error should have been handled by catch block,

TypeError: Cannot read property in Nodejs

my code:
var firstName = typeof(data.payload.firstName) == 'string' && data.payload.firstName.trim().length >0 ? data.payload.firstName.trim() : false;

but when it runs in git bash, I got the err as :
`$ node index.js
It's listening on 3200 in staging mode
It's listening on 3201 in staging mode
file:///E:/Learn/lib/handlers.js:29
var firstName = typeof(data.payload.firstName) == 'string' &&
data.payload.firstName.trim().length >0 ? data.payload.firstName.trim() : false;
^

TypeError: Cannot read property 'firstName' of undefined
at Object.handlers._users.post (file:///E:/Learn/lib/handlers.js:29:41)
at handlers.users (file:///E:/Learn/lib/handlers.js:16:37)
at IncomingMessage. (file:///E:/Learn/index.js:107:21)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (internal/streams/readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)`

how to resolve this?

fs.truncate with a descriptor is deprecated.

In section three, we create the update functionality and are instructed to use fs.truncate but I received a warning from node:

(node:29626) [DEP0081] DeprecationWarning: Using fs.truncate with a file descriptor is deprecated. Please use fs.ftruncate with a file descriptor instead.

Open SSL

In OpenSSL website I could only see download for mac os or osx whatever but it is not present in windows so what can I do

Session 7 - using child Processes

//---------------------------------list logs
cli.responders.listLogs = function () {
cli.verticalSpace();
var ls = childProcess.spawn('ls', ['./.logs/']);
ls.stdout.on('data', function (dataObj) {
// Explode into separate lines
var dataStr = dataObj.toString();
var logFileNames = dataStr.split('\n');
logFileNames.forEach(function (logFileName) {
if (typeof (logFileName) == 'string' && logFileName.trim().length > 0 && logFileName.indexOf('-') > -1) {
console.log(logFileName.trim().split('.')[0]);
cli.verticalSpace();
}
});
});
};

It says that spawn LS is ENOENT, i tried to use the entire coppied path to .logs but it does not work, if i find a fix i will post it here, for now its not working for me at least.

delete function incorrect

The-NodeJS-Master-Class/Section 3/Storing Data/lib/data.js
the delete method in this file is coded incorrectly. It has reference to variable data while it should not.

handlers.js

Hello, I am having trouble creating a user on Section 3 - Service 2 Users.
Everything is fine as I use postman without putting anything on the body which results to
this output {'Error' : 'Missing required fields'} which is right.
However, when I provide the values on the body, I followed it exactly as you have provided and still the output is '(Error' : 'Missing required fields'}. I traced and check our codes and they are identical. So I tried to run your code that I downloaded and the same output was displayed.
I noticed that on your video on Section 3 - Service 2 Users at 30:53 aside from the body
you have a value on the header. If that is what I missed what should I put on the key and value before I press send? Thank you.

Section 2 - Common Node Conventions

Hi, I tried running npm install while following the code added in package.json and I get this error.

npm ERR! code ETARGET
npm ERR! notarget No matching version found for [email protected].
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.
npm ERR! notarget
npm ERR! notarget It was specified as a dependency of 'Common Node Conventions'
npm ERR! notarget

FYI.

So I just tried to use "jokes 0.0.2" just like in your tutorial and it works.

ReferenceError: __dirname is not defined

code in the datafile is lib.baseDir = path.join(__dirname, '/../.data/');
in git bash it indicates when run for test err,

$ node index.js
file:///E:/Learn/lib/data.js:15
lib.baseDir = path.join(__dirname, '/../.data/');
                        ^

 ReferenceError: __dirname is not defined

How to get clear on this?

File Upload

How to upload files without 3rd party modules?

New In Section 4, ( Lecture Title: Page 2 Create an Account ) related

An error is popping up when i go to the localhost:3000

app.js:87 Uncaught TypeError: Cannot read property 'addEventListener' of null at Object.app.bindForms (app.js:87) at Object.app.init (app.js:142) at window.onload (app.js:147) app.bindForms @ app.js:87 app.init @ app.js:142 window.onload @ app.js:147 load (async) (anonymous) @ app.js:146

and after that clicking on create account CSS, js, logo nothing loads...

GET http://localhost:3000/account/public/app.js net::ERR_ABORTED 404 (Not Found) create:16 GET http://localhost:3000/account/public/app.css net::ERR_ABORTED 404 (Not Found) create:26 GET http://localhost:3000/account/public/logo.png 404 (Not Found)

please help @pirple-author

Trying to build include function

Function helpers.getHTMLAsset is from the course, I have created helpers.resolveIncludes to take the HTML string and search for "filename.html" then load the filename.html and return a new string to the browser.

I am getting "undefined" for finalStr in function below however the string is correct when console logged before the return in helpers.resolveIncludes. I am certain this is a Scope related issue but have not been able to find the problem for hours now...

Thank you for any assistance !

// ============================================================
// Get the contents of an HTML file as a string, and check for and resolve server side includes
// ============================================================
helpers.getHTMLAsset = function(fileName, callback) {
fileName =
typeof fileName == "string" && fileName.length > 0 ? fileName : false;
if (fileName) {
var publicDir = path.join(__dirname, "/../public/");
fs.readFile(publicDir + fileName, "utf8", function(err, str) {
if (!err && str && str.length > 0) {
var finalStr = "";
finalStr = helpers.resolveIncludes(str);
console.log("Received FinalString: " + finalStr);
callback(false, finalStr);
} else {
callback("Filename could be found");
}
});
} else {
callback("A valid filename name was not specified");
}
};

// ==================================================================
// Include files as needed
// =================================================================
helpers.resolveIncludes = function(str) {
var result = "";

// Verify we have a valid String
var str = typeof str == "string" && str.length > 0 ? str : false;
if (str) {
var startPos = str.indexOf("");
if (startPos > -1) {
// Search for ending tag
var endPos = str.indexOf("", startPos);
if (endPos > -1) {
//console.log("Found closing tag at pos: " + endPos);

    // Extract include file name
    var fileName = str.substring(startPos + 10, endPos - 1);

    // Load the file
    helpers.getHTMLTemplate(fileName, function(err, fileData) {
      if (!err && fileData && fileData.length > 0) {
        // Insert include file
        var strBefore = str.substring(0, startPos);
        var strAfter = str.substring(endPos + 10);

        // New String with file included
        result = strBefore + fileData + strAfter;

        // console.log("Returning: " + str);

        // Callback new String
        return result;
      } else {
        // Error: File not found or File empty
        return str;
      }
    });
  } else {
    // Closing </include> not found
    return str;
  }
} else {
  // Opening <include> tag not found
  return str;
}

} else {
// String is invalid
return str;
}
};

Why we are not sending headers on app.bindForms()?

Why we are not sending the header in the first parameter, is undefined and should send the token as header it makes than authenticate fails

            app.client.request( undefined, path, method, queryStringObject, payload, function( statusCode, responsePayload ) {
            } );

openssl

Can I use the cert.pem and key.pem from the source code instead of generating a new one?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.