且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

node06---npm、silly-datetime、路径问题

更新时间:2022-09-12 09:45:25

node06---npm、silly-datetime、路径问题
我们刚才学习了,模块就是一些功能的封装,所以一些成熟的、经常使用的功能,都有人封装成为了模块。并且放到了社区中,供人免费下载。
这个伟大的社区,叫做npm。 也是一个工具名字  node package management
https://www.npmjs.com/

去社区搜索需求,然后点进去,看api。
如果要配置一个模块,那么直接在cmd使用
1npm install 模块名字
就可以安装。 模块名字全球唯一。安装的文件在一个node_modules文件夹中,
安装的时候,要注意,命令提示符的所在位置。
node06---npm、silly-datetime、路径问题

08.js

var sd = require("silly-datetime");

//需要使用一个日期时间,格式为 20150920110632
var ttt = sd.format(new Date(), 'YYYYMMDDHHmm');

package.json

node06---npm、silly-datetime、路径问题
/* 跟08.js 在一个目录。

我们可以用package.json来管理依赖。
在cmd中,08.js文件所在文件夹,使用npm  init可以初始化一个package.json文件,用回答问题的方式生成一个新的package.json文件。
使用 08.js文件所在文件夹 : npm  install
将能根据package.json安装08.js所有的依赖。
npm也有文档,这是package.json的介绍:
https://docs.npmjs.com/files/package.json
*/
{
  "name": "day2",
  "version": "1.0.0",
  "description": "ziji zuo de xia waner de",
  "main": "08.js",
  "directories": {
    "test": "test"
  },
  "dependencies": {
    "silly-datetime": "^0.1.0"  /*^表示固定只使用0.x.x的版本,不使用1.x.x,2.x.x*/
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "good",
    "greet"
  ],
  "author": "kaola",
  "license": "ISC"
}
node06---npm、silly-datetime、路径问题

 

node06---npm、silly-datetime、路径问题
require()别的js文件的时候,将执行那个js文件。
注意:
require()中的路径,是从当前这个js文件出发,根据相对路径,找到别人。而fs是从命令提示符找到别人。
所以,桌面上有一个a.js, test文件夹中有b.js、c.js、1.txt
a要引用b:
var b = require(“./test/b.js”);
b要引用c:
var b = require(“./c.js”);
但是,fs等其他的模块用到路径的时候,都是相对于cmd命令光标所在位置。
所以,在b.js中想读1.txt文件,推荐用绝对路径:
fs.readFile(__dirname + "/1.txt",function(err,data){
   console.log(__dirname);//当前文件的绝对路径,E:\360data\重要数据\桌面\test,跨平台兼容,linux也可以兼容
    if(err) { throw err; }
    console.log(data.toString());
});
node06---npm、silly-datetime、路径问题

 silly-datetime源码

node06---npm、silly-datetime、路径问题
(function(root, factory) {
  'use strict';
  /* istanbul ignore else  */
  if (typeof exports === 'object') {
    // CommonJS
    module.exports = factory();
  } else if (typeof define === 'function' && define.amd) {
    // AMD
    define(function() {
      return factory();
    });
  } else if (typeof define === 'function' && define.cmd) {
    // CMD
    define(function(require, exports, module) {
      module.exports = factory();
    });
  } else {
    // Global Variables
    root.ResizeImage = factory();
  }
})(this, function () {
  'use strict';

  var out = {};

  /**
   * 将输入的任意对象转换成 Date,如果装换失败将返回当前时间
   * @param  {any} datetime 需要被格式化的时间
   * @return {Date}         转换好的 Date
   */
  function getDateObject(datetime) {
    var t = datetime instanceof Date ? datetime : new Date(datetime);
    if (!t.getDate()) {
      t = new Date();
    }
    return t;
  }

  /**
   * 格式化时间
   * @param  {Date}   datetime 需要被格式化的时间
   * @param  {string} format   格式化字符串,默认为 'YYYY-MM-DD HH:mm:ss'
   * @return {string}          格式化后的时间字符串
   */
  out.format = function (datetime, format) {
    var t = getDateObject(datetime);
    var hours, o, i = 0;
    format = format || 'YYYY-MM-DD HH:mm:ss';
    hours = t.getHours();
    o = [
      ['M+', t.getMonth() + 1],
      ['D+', t.getDate()],
      // H 24小时制
      ['H+', hours],
      // h 12小时制
      ['h+', hours > 12 ? hours - 12 : hours],
      ['m+', t.getMinutes()],
      ['s+', t.getSeconds()],
    ];
    // 替换 Y
    if (/(Y+)/.test(format)) {
      format = format.replace(RegExp.$1, (t.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    // 替换 M, D, H, h, m, s
    for (; i < o.length; i++) {
      if (new RegExp('(' + o[i][0] + ')').test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? o[i][1] : ('00' + o[i][1]).substr(('' + o[i][1]).length));
      }
    }
    // 替换 a/A 为 am, pm
    return format.replace(/a/ig, hours > 11 ? 'pm' : 'am');
  };



  /**
   * CONST and VAR for .fromNow
   */
  // 预设语言:英语
  var LOCALE_EN = {
    future: 'in %s',
    past: '%s ago',
    s: 'a few seconds',
    mm: '%s minutes',
    hh: '%s hours',
    dd: '%s days',
    MM: '%s months',
    yy: '%s years'
  };
  // 预设语言:简体中文
  var LOCALE_ZH_CN = {
    future: '%s内',
    past: '%s前',
    s: '几秒',
    mm: '%s分钟',
    hh: '%s小时',
    dd: '%s天',
    MM: '%s月',
    yy: '%s年'
  };
  // 当前本地化语言对象
  var _curentLocale = {};


  /**
   * 修改本地化语言
   * @param  {string|Object}   string: 预设语言 `zh-cn` 或 `en`;Object: 自定义 locate 对象
   * @return {Object}          this
   */
  out.locate = function (arg) {
    var newLocale, prop;
    if (typeof arg === 'string') {
      newLocale = arg === 'zh-cn' ? LOCALE_ZH_CN : LOCALE_EN;
    } else {
      newLocale = arg;
    }
    for (prop in newLocale) {
      if (newLocale.hasOwnProperty(prop) && typeof newLocale[prop] === 'string') {
        _curentLocale[prop] = newLocale[prop];
      }
    }
    return out;
  };
  // 初始化本地化语言为 en
  out.locate('');



  /**
   * CONST for .fromNow
   */
  // 各计算区间
  var DET_STD = [
    [ 'yy', 31536e6 ], // 1000 * 60 * 60 * 24 * 365 一年月按 365 天算
    [ 'MM', 2592e6 ],  // 1000 * 60 * 60 * 24 * 30 一个月按 30 天算
    [ 'dd', 864e5 ],   // 1000 * 60 * 60 * 24
    [ 'hh', 36e5 ],    // 1000 * 60 * 60
    [ 'mm', 6e4 ],     // 1000 * 60
    [ 's',  0 ],       // 只要大于等于 0 都是秒
  ];

  /**
   * 计算给出时间和当前时间的时间距离
   * @param  {Date}   datetime 需要计算的时间
   * @return {string}          时间距离
   */
  out.fromNow = function (datetime) {
    var det = +new Date() - (+getDateObject(datetime));
    var format, str, i = 0, detDef, detDefVal;
    if (det < 0) {
      format = _curentLocale.future;
      det = -det;
    } else {
      format = _curentLocale.past;
    }
    for (; i < DET_STD.length; i++) {
      detDef = DET_STD[i];
      detDefVal = detDef[1];
      if (det >= detDefVal) {
        str = _curentLocale[detDef[0]].replace('%s', parseInt(det/detDefVal, 0) || 1);
        break;
      }
    }
    return format.replace('%s', str);
  };

  return out;
});
node06---npm、silly-datetime、路径问题

 


本文转自农夫山泉别墅博客园博客,原文链接:http://www.cnblogs.com/yaowen/p/7033925.html,如需转载请自行联系原作者