在被定义之前使用“require”
我开始学习Node.js. 我购买了Marc Wandscheider写的手册。 我下载了使用它的工具,我也下载了支架。
我正在尝试一个示例脚本,但是我得到了两个不明白的错误,而这些错误并不存在于指南中。
第一个错误告诉我:
在被定义之前使用“require”
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>
而第二(在括号内):
缺less严格的使用说明
我在互联网上看到,我可以添加该行
"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);
这些错误实际上是JSHINT过程的validation良好代码的build议。 括号可能在幕后使用它。 如果你告诉jshint你正在写节点,那么require会变成一个全局variables,所以它不会给出这个错误。 尝试运行这个代码,并提供一些关于JSHINT的警告, 以及 使用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);
在编写一个gulp文件时,我遇到了来自Brackets的JSLint窗口的类似警告。 我就是这样解决他们的:
Problems × 1 'require' was used before it was defined.
require函数是在其他地方定义的,特别是作为Node.js的一部分,所以为了解决这个警告,通过在JavaScript文件的顶部添加这个来标记为全局的:
/* global require */
请参阅http://jslinterrors.com/a-was-used-before-it-was-defined
Missing 'use strict' statement
我通过使用立即调用的函数expression式解决了这个问题:
(function () { "use strict"; // The rest of the code }());
见http://jslinterrors.com/move-the-invocation-into-the-parens-that-contain-the-function
Combine this with the previous 'var' statement
这一个很简单。 代替
var body = 'Thanks for calling!'; var content_length = body.length;
使用
var body = 'Thanks for calling!', content_length = body.length;