Kevin
Kevin

Reputation: 427

'require' was used before it was defined

I'm starting to study Node.js. I purchased the manual written by Marc Wandscheider. I downloaded the tools to use it and I also downloaded Brackets.

I'm trying a sample script, but I get two errors that do not understand and that are not present in the guide.

The first error tells me that:

'require' was used before it was defined

C:\node> node debug web.js
<Debugger listening on port 5858>
connecting ... ok
break in C:\node\web.js: 1
   1 var http = require ("http");
   2
   3 process_request function (req, res) {
debug>

while the second (in Brackets):

missing use strict statement

I saw on the internet that I can add the line

"use strict";

But the guide does not use it - is it required?

How can I fix these issues?

entire code

var http = require("http");

function process_request(req, res) {

    var body = 'Thanks for calling!';
    var content_length = body.length;
        res.writeHead(200, {
            'Content-Length': content_length,
            'Content-Type': 'text/plain'
        });
    res.end(body);
}

var s = http.createServer(process_request);
s.listen(8080);

Upvotes: 5

Views: 11623

Answers (2)

Malice
Malice

Reputation: 3977

I encountered similar warnings from the JSLint window in Brackets while writing a gulp file. This is how I resolved them:

Problems × 1 'require' was used before it was defined.

The require function is defined elsewhere, specifically as part of Node.js so to resolve the warning, mark it as a global by adding this at the top of your JavaScript file:

/* global require */

See http://jslinterrors.com/a-was-used-before-it-was-defined

Missing 'use strict' statement

I resolved this by using an immediately invoked function expression:

(function () {
    "use strict";

    // The rest of the code
}());

See http://jslinterrors.com/move-the-invocation-into-the-parens-that-contain-the-function

Combine this with the previous 'var' statement

This one is straightforward. Instead of

var body = 'Thanks for calling!';
var content_length = body.length;

use

var body = 'Thanks for calling!',
    content_length = body.length;

Upvotes: 2

pdjota
pdjota

Reputation: 3243

Those errors are actually suggestions of the JSHINT process to validate good code. Brackets is using it behind the scene probably. If you tell jshint you are writing for node then require becomes a global variable so it does not give that error. Try running this code with some warnings for JSHINT some article with proper explanation on using JSHINT

/*jshint node:true */
'use strict';
var http = require('http');

function process_request(req, res) {

    var body = 'Thanks for calling!';
    var content_length = body.length;
        res.writeHead(200, {
            'Content-Length': content_length,
            'Content-Type': 'text/plain'
        });
    res.end(body);
}

var s = http.createServer(process_request);
s.listen(8080);

Upvotes: 6

Related Questions