coffeescript找不到localStorage

时间:2013-05-20 07:06:59

标签: macos coffeescript local-storage

我正在尝试自学coffeescript,但在尝试使用localStorage时却不尽如人意。

$ coffee detail_view.coffee 
ReferenceError: localStorage is not defined
  at isLoggedIn (/Users/me/workspace/hero/html_client/detail_view.coffee:12:18, <js>:5:13)
  at Object.<anonymous> (/Users/me/workspace/hero/html_client/detail_view.coffee:225:4, <js>:144:7)
  at Object.<anonymous> (/Users/me/workspace/hero/html_client/detail_view.coffee:164:4)
  at Module._compile (module.js:456:26)

detail_view.coffee中的行是:

(localStorage.getItem("a_key") isnt null) and (localStorage.getItem("b_key") isnt null)

我已尝试通过npm安装localstorage,但它没有帮助。 即

$ sudo npm -g install localstorage
npm http GET https://registry.npmjs.org/localstorage
npm http 404 https://registry.npmjs.org/localstorage
localStorage@1.0.2 /usr/local/lib/node_modules/localStorage

$ echo 'export PATH=/usr/local/lib/node_modules/localStorage:$PATH' >> ~/.profile
$ source ~/.profile
$ coffee detail_view.coffee 
ReferenceError: localStorage is not defined
  at isLoggedIn (/Users/me/workspace/hero/html_client/detail_view.coffee:12:18, <js>:5:13)
  at Object.<anonymous> (/Users/me/workspace/hero/html_client/detail_view.coffee:225:4, <js>:144:7)
  at Object.<anonymous> (/Users/me/workspace/hero/html_client/detail_view.coffee:164:4)
  at Module._compile (module.js:456:26)

我错过了什么?

1 个答案:

答案 0 :(得分:1)

localStorage是网络浏览器提供的功能。在node.js中它不存在。这意味着如果您在node.js运行的脚本中引用localStorage,则会出现错误。

即使你安装了你提到的localStorage npm模块,你也需要它来使用它。

localStorage = require('localStorage')
localStorage.getItem 'a_key'