"require" was used before its definition

I'm starting to learn Node.js. I acquired a guide written by Mark Wandscheider. I downloaded the tools to use it, and I also downloaded the brackets.

I am trying to create a sample script, but I am getting two errors that do not understand and which are missing from the manual.

The first error tells me that:

'require' was used before its definition

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> 

and the second (in brackets):

no use of strict instructions

I saw on the Internet that I can add a line

 "use strict"; 

But management does not use it - is it required?

How can I fix these problems?

all 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); 
+5
source share
2 answers

These errors are actually JSHINT process recommendations for verifying the correct code. Brackets probably use it behind the scenes. If you specify the jshint you are writing for node, then require becomes a global variable, so it does not give this error. Try running this code with some warnings for some article JSHINT with an appropriate explanation when 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); 
+6
source

I came across similar warnings from the JSLint window in brackets when writing a gulp file. Here is how I resolved them:

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

The require function is defined elsewhere, in particular, as part of Node.js, so to eliminate the warning, mark it as global by adding it 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 using the function call immediately called:

 (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

It's simple. Instead

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

use

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

Source: https://habr.com/ru/post/1210676/


All Articles