Category: Node.js

  • Cannot set headers after they are sent to the client

    When you are using Node.js with Express and you’ve received the dreaded error [err_http_headers_sent]: cannot set headers after they are sent to the client where do you even begin with err_http_headers_sent’. This article will explore common causes of this error, such as calling res.writeHead, res.write, or res.redirect.

    A problem occurs when servers send out headers after the message has been received by the client. Node JS applications send multiple responses to the same request – eg. calling the request twice instead of a single request with one response res.send headers.

    (more…)

  • Uncaught ReferenceError: require is not defined

    When you’re first starting out with Node js, it might be a bit confusing because you are most likely accustomed to writing JavaScript code for the web browser. When Node js is the server, the syntax is similar but there are a few differences around how other JavaScript files and modules are included. When writing on the server side you may include files as follows: require(‘./mysharedfile’);.

    (more…)

  • Updating all npm packages in a Node.js project

    I have two common scenarios where I want to update my npm packages. First, my existing project needs a package update or secondly I’ve started a new project and since I’m lazy I’ve copied my package.json file from one project to this project. I’ve found two different ways to perform this.

    1. Changing the versions to * in my packages.json
    2. Using the npm-check-updates package

    Let’s examine in more details each way.

    (more…)

  • Passing/reading command line arguments with Node.js

    It’s quite common when running an application to want to pass arguments to the program to define how it should run when executed. This is no different then with Node.js. To accomplish this I like to use one of two ways:

    1. Reading the JavaScript array node js process.argv and manually parsing the variables
    2. Using an npm library such as minimist that helps simplify and (in my opinion) parses them into a nice JavaScript variable

    Let’s take a look at both ways.

    (more…)

  • Setup routes in Node.js with Express.js and Jade with controllers, models, and views

    I like the structure of Model View Controller (MVC) and I wanted to apply it to my Node.js projects.

    I’ve written previous articles about Node using Jade Templates with Express, but I didn’t go into much details about code organization; let’s do that now.

    (more…)